C ++抽象基类模板
这段代码有什么问题?
template <class T>
class A
{
private:
T a;
public:
A(): a(0) {}
virtual ~ A() = 0;
};
template <class T>
class A;
template <class T>
class B : public A<T>
{
private :
T b;
public:
B() : A<T>() {}
virtual ~B(){}
};
int _tmain(int argc, _TCHAR* argv[])
{
B <double> bb;
return 0;
}
错误 LNK2019:无法解析的外部符号“public: virtual __thiscall A::~A(void)” (??1?$A@N@@UAE@XZ) 在函数“public: virtual __thiscall B::~B(void)”中引用)" (??1?$B@N@@UAE@XZ)
What´s the wrong in this code?
template <class T>
class A
{
private:
T a;
public:
A(): a(0) {}
virtual ~ A() = 0;
};
template <class T>
class A;
template <class T>
class B : public A<T>
{
private :
T b;
public:
B() : A<T>() {}
virtual ~B(){}
};
int _tmain(int argc, _TCHAR* argv[])
{
B <double> bb;
return 0;
}
error LNK2019: unresolved external symbol "public: virtual __thiscall A::~A(void)" (??1?$A@N@@UAE@XZ) referenced in function "public: virtual __thiscall B::~B(void)" (??1?$B@N@@UAE@XZ)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您将
A
的析构函数声明为纯虚函数。这一切都很好,如果您想保证该类永远不会被实例化,那么这可以被认为是很好的实践。但是,您仍然必须在代码中的某个位置定义A::~A()
,因为B
的析构函数会自动调用A::~A()< /code> 在
B
对象上。由于您将其声明为纯虚拟,因此您无法像使用~B
那样内联定义它;您必须将其定义包含在类定义之外。You declare
A
's destructor as pure virtual. This is all well and good, and can be considered good practice if you want to guarantee the class is never instantiated. However, you must still defineA::~A()
somewhere in your code, asB
's destructor automatically callsA::~A()
on theB
object. Since you declared it pure virtual, you cannot define it inline as you did with~B
; you must include it's definition outside the class definition.您需要提供基类析构函数的实现。即使析构函数被声明为纯虚函数,也需要实现来销毁派生类。
You need to provide implementation for base class destructor. Even if destructor is declared pure virtual, implementation is required to destroy derived classes.
你的超类析构函数不应该是纯虚拟的,而只是虚拟的。
B 的析构函数会自动尝试调用 A 的析构函数。
Your superclass destructor should not be pure virtual, just virtual.
The destructor of B will automatically try to call the destructor of A.