【问题标题】:Undefined reference to inherited function对继承函数的未定义引用
【发布时间】:2016-04-09 16:23:22
【问题描述】:

我正在实施 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 toCompareVal >::compare(Array, Array)' /tmp/ccCLm8Gn.o:(.rodata._ZTV9HeuristicI5ArrayIiEE[_ZTV9HeuristicI5ArrayIiEE]+0x10):未定义对“启发式 >::getHeuristic(Node >, Node >)”的引用 collect2:错误:ld 返回 1 个退出状态 块引用

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

【问题讨论】:

    标签: c++ templates inheritance


    【解决方案1】:

    所有虚函数都需要定义,即使它们在子类中被覆盖。如果您不想在基类中实现它们,并强制子类覆盖您应该在基类中使它们抽象的函数,例如

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-29
      • 2012-03-13
      • 2015-04-08
      • 2014-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多