[英]undefined reference
我有這些類(和功能):
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 ∑
}
};
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 to
Factory::binOp()'
list.cpp:(.text._ZN15SpecializedListIiE3sumEv[SpecializedList::sum()]+0x2c): `Factory::zero()'
collect2: ld returned 1 exit status
有人知道為什么嗎?
我正在谷歌搜索錯誤消息的相關部分,當代碼分散在不同的文件中時,它看起來與問題有關。
我現在把所有東西都放在一個文件里。
兩個問題:
binOp()
。zero()
。解決方案:
通過將純說明符指定為,在Factory
中使 function binOp()
成為純虛擬 function:
virtual A (*binOp(void))(A,A) = 0; //"=0" is called pure-specifier //^^^^^^ this makes the function virtual
現在不需要定義它(就鏈接器錯誤而言)。 或者,您也可以定義它。
在工廠中聲明一個 function zero()
。 如果您不使其成為純虛擬,則必須對其進行定義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.