未定义参考

时间:2011-05-24 12:39:08

标签: c++

我有这些类(和函数):

template <class A>
class Factory{
  public:
    A (*binOp(void))(A,A);
};
int sum(int a, int b){
  return a + b;
}
class IntFactory : public Factory<int>{
  public:
    int (*binOp(void))(int,int){
      return &sum;
    }
};
template <class A>
class SpecializedList{
  protected:
    List<A>* list;
    Factory<A>* factory;
  public:
    SpecializedList(List<A>* list,Factory<A>* factory){
      this -> list = list;
      this -> factory = factory;
    }
    A sum(){
      return (list -> foldLeft(factory -> zero(), factory -> binOp()));
    }
};

// in main
SpecializedList<int>* sl = new SpecializedList<int>(join1 -> getList(),new IntFactory());
cout << sl -> sum() << endl;

我收到错误:

/tmp/ccxdiwUF.o: In function SpecializedList<int>::sum()':
list.cpp:(.text._ZN15SpecializedListIiE3sumEv[SpecializedList<int>::sum()]+0x19): undefined reference toFactory::binOp()'
list.cpp:(.text._ZN15SpecializedListIiE3sumEv[SpecializedList::sum()]+0x2c):  `Factory::zero()'
collect2: ld returned 1 exit status
有人知道为什么吗? 我在google搜索错误消息的相关部分,看起来它与问题有关,当一个代码散布在不同的文件中时。我现在把所有东西都放在单个文件中。

1 个答案:

答案 0 :(得分:6)

两个问题:

  • 工厂未定义函数binOp()
  • 工厂甚至没有zero()
  • 功能

解决方案:

  • 通过将pure-specifier指定为binOp(),使函数Factory成为纯虚函数:

     virtual A (*binOp(void))(A,A) = 0; //"=0" is called pure-specifier
    //^^^^^^ this makes the function virtual
    

    现在没有需要来定义它(就链接器错误而言)。或者,您也可以定义它。

  • 在Factory中声明函数zero()。如果你不使它成为纯虚拟,那么必须定义它。