模板链接器错误 类
Linker error with template classes
我在编译模板时遇到一个奇怪的错误 类。这是我的最小示例:
#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()
。
我在编译模板时遇到一个奇怪的错误 类。这是我的最小示例:
#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()
。