2016-11-29 61 views
3

我需要製作一般的Robot,它將在一般的Surface上找到路徑。錯誤模板派生類中的「純虛函數調用」

因此,這裏是我的Surface接口:

template <typename P> 
class Surface { 
public: 
    virtual int distance(const P& from, const P& to) const = 0; 
    virtual bool check(const vector<P>& path, const P& from, const P& to) const = 0; 
    virtual vector<P> lookAround(const P& at) const = 0; 
}; 

在這裏,我創建一個簡單的PlanarSurface

class PlanarSurface : public Surface<pair<int, int>> { 
public: 
    using point_type = pair<int, int>; 
    int distance(const point_type& from, const point_type& to) const override { 
     return to.first - from.first + to.second - from.second; 
    } 

    bool check(const vector<point_type>& path, 
       const point_type& from, 
       const point_type& to) const override { 
     return true; // there would be the check 
    } 

    vector<point_type> lookAround(const point_type& at) const override { 
     vector<point_type> result; 
     //... 
     return result; 
    } 
}; 

現在我創建一個抽象類Robot讓每一位用戶實現機器人將擴展它:

template <typename P> 
class Robot { 
public: 
    Robot(const Surface<P>& s): surface(s) {} 
    vector<P> findPath(const P& from, const P& to) { 
     auto path = searchPath(from, to); 
     if (surface.check(path, from, to)) { 
      return path; 
     } 
     throw runtime_error("path not found or incorrect"); 
    } 
private: 
    virtual vector<P> searchPath(const P& from, const P& to) = 0; 
protected: 
    const Surface<P>& surface; 
}; 

There searchPath私有方法將負責自定義搜索算法,在Robot的子項中定義。 假設我有一個:

template <typename P> 
class MyRobot: public Robot<P> { 
public: 
    MyRobot(Surface<P> m): Robot<P>(m) {} 
private: 
    vector<P> searchPath(const P& from, const P& to) override { 
     vector<P> result; 
     // ... 
     // use one of surface's virtual methods 
     auto dist = this->surface.distance(from, to); // Pure virtual function called! 
     cout << dist << endl; 
     // ... 
     return result; 
    } 
}; 

最後的main功能:

int main(const int argc, const char **argv) { 
    PlanarSurface plane; 
    MyRobot<pair<int, int>> robot(plane); 
    robot.findPath({1,2}, {3,4}); 
    return 0; 
} 

所以問題是,作爲參考surface存儲在基地Robot類,我們不能確定它的類型與一些衍生的Surface類。所以參考的類型只能是Surface<P, M>

我們需要使用surfacedistancelookAround方法在我們的搜索算法Robot的每個孩子。但在Surface<P, M>他們是純粹的虛擬。他們只能在Surface<P, M>的孩子中實施。

請幫幫我!也許我錯過了一些東西明顯..

回答

4

的錯誤是在這裏:

MyRobot(Surface<P> m) : Robot<P>(m) {} 
     ^^^^^^^^^^^^ value 

改變它接受一個參考,而不是

MyRobot(Surface<P>& m) : Robot<P>(m) {} 

有趣的是這兩個MSVC和GCC沿

線診斷此問題

抽象參數無效

雖然鏗鏘甚至沒有發出關於此的警告(在寫這篇文章的時候 - 4.0)

+1

哦,當然你是對的!謝謝! –

相關問題