我在编译模板类时遇到一个奇怪的错误。这是我的最小示例:
#include <iostream>
using namespace std;
template<class T>
class A{
T element;
protected:
virtual bool empty() const noexcept = 0;
};
template<class T>
class B : public A<T> {
public:
bool tryOP(T &element) const {
if (A<T>::empty())
return false;
else
{
std::cout << "Operation" << std::endl;
return true;
}
}
};
template <class T>
class C : public B<T> {
private:
bool empty() const noexcept override{
return true;
}
};
int main(){
int n = 0;
C<int> c;
c.tryOP(n);
}
错误:
/tmp/ccJvMBCZ.o: In function B::tryOP(int&) const: A.cpp:(.text._ZNK1BIiE5tryOPERi[_ZNK1BIiE5tryOPERi]+0x18): undefined reference to `A::empty() const' collect2: error: ld returned 1 exit status
为什么未定义对 empty() 的引用?它就在那里!
最佳答案
方法A<T>::empty()
是抽象方法,所以不能调用,但是可以调用this->empty()
.
关于c++ - 模板类的链接器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45263650/