2016-04-09 56 views
0

我正在實現A *算法來解決一些問題--8拼圖問題和另一個問題。對於一個明星,我實現了在A_star.hpp常見三種:對繼承函數的未定義引用

template <class U> 
class Heuristic{ 
public: 
    virtual int getHeuristic(Node<U> currNode, Node<U> target); 
}; 

template <class V> 
class NextNodeGenerator{ 
public: 
    virtual vector<pair<V, int> > generate(Node<V> curr); 
}; 

template <class W> 
class CompareVal{ 
public: 
    virtual bool compare(W val1, W val2); 
}; 

爲解決8數碼問題,我實現了三個子類在prob2.cpp上述每個泛型類:

template <class hT> 
class PuzzleHeuristic: public Heuristic<hT>{ 
public: 
    virtual int getHeuristic(Node<hT> currNode, Node<hT> target){ 
     //Code for getHeuristic 
    } 
}; 

template <class cT> 
class PuzzleCompareVal: public CompareVal<cT>{ 
public: 
    virtual bool compare(cT val1, cT val2){ 
     //Code for compare 
    } 
}; 

template <class nT> 
class PuzzleNNG: public NextNodeGenerator<nT>{ 
public: 
    virtual vector<pair<nT, int> > generate(Node<nT> curr){ 
     //Code for generate 
} 

在A_star.hpp,我也有一個愛仕達類:

template <class Y> 
class AStar{ 
    Heuristic<Y> *h; 
    NextNodeGenerator<Y> *nng; 
    CompareVal<Y> *comp; 

public: 

    void setHeuristic(Heuristic<Y> *hParam){ 
     h = hParam; 
    } 

    void setNNG(NextNodeGenerator<Y> *nngParam){ 
     nng = nngParam; 
    } 

    void setCompareVal(CompareVal<Y> *compParam){ 
     comp = compParam; 
    } 

    vector<Node<Y> > solve(Y start, Y target){ 
     //Code for solve 
    } 

在prob2.cpp我的main()函數,我創造了一個愛仕達對象(數組是我已經定義的模板類分開):

int main() 
{ 
    PuzzleHeuristic<Array<int> > pH; 
    PuzzleCompareVal<Array<int> > pCV; 
    PuzzleNNG<Array<int> > pNNG; 

    AStar<Array<int> > aStar; 
    aStar.setHeuristic(&pH); 
    aStar.setNNG(&pNNG); 
    aStar.setCompareVal(&pCV); 

    vector<Node<Array<int> > > answer = aStar.solve(start, target); 
} 

在編譯時,我得到了以下錯誤:

/tmp/ccCLm8Gn.o:(.rodata._ZTV17NextNodeGeneratorI5ArrayIiEE[_ZTV17NextNodeGeneratorI5ArrayIiEE]+0x10): undefined reference to NextNodeGenerator<Array<int> >::generate(Node<Array<int> >)' /tmp/ccCLm8Gn.o:(.rodata._ZTV10CompareValI5ArrayIiEE[_ZTV10CompareValI5ArrayIiEE]+0x10): undefined reference to CompareVal >::compare(Array, Array)' /tmp/ccCLm8Gn.o:(.rodata._ZTV9HeuristicI5ArrayIiEE[_ZTV9HeuristicI5ArrayIiEE]+0x10): undefined reference to `Heuristic >::getHeuristic(Node >, Node >)' collect2: error: ld returned 1 exit status Blockquote

我懷疑問題是由於模板函數的繼承。什麼可能導致錯誤?

回答

2

所有虛函數都需要定義,即使它們在子類中被覆蓋。如果你不希望實現他們在基類中,並迫使子類覆蓋功能,你應該讓他們抽象在基類,例如像

template <class V> 
class NextNodeGenerator{ 
public: 
    virtual vector<pair<V, int> > generate(Node<V> curr) = 0; 
    //             ^^^^ 
    // This is what makes the function an abstract function 
};