未定义的对继承函数的引用

时间:2016-04-09 16:23:23

标签: c++ templates inheritance

我正在实施A *算法来解决一些问题 - 8个难题和另一个问题。对于A Star,我在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 Puzzle问题,我在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中,我还有一个AStar类:

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()函数中,我创建了一个AStar对象(Array是我单独定义的模板类):

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):对NextNodeGenerator<Array<int> >::generate(Node<Array<int> >)' /tmp/ccCLm8Gn.o:(.rodata._ZTV10CompareValI5ArrayIiEE[_ZTV10CompareValI5ArrayIiEE]+0x10): undefined reference to的未定义引用CompareVal&gt; :: compare(Array,Array)'   /tmp/ccCLm8Gn.o:(.rodata._ZTV9HeuristicI5ArrayIiEE[_ZTV9HeuristicI5ArrayIiEE]+xx10):未定义引用`Heuristic&gt; :: getHeuristic(Node&gt;,Node&gt;)'   collect2:错误:ld返回1退出状态   块引用

我怀疑问题是由于模板函数中的继承造成的。可能导致错误的原因是什么?

1 个答案:

答案 0 :(得分:4)

所有虚函数都需要定义,即使它们在子类中被覆盖也是如此。如果你不想在基类中实现它们,并强制子类重写函数,你应该在基类中使它们成为 abstract ,例如

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 
};