C ++ abstract base class templates
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;
retu开发者_开发百科rn 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)
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 define A::~A()
somewhere in your code, as B
's destructor automatically calls A::~A()
on the B
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.
Your superclass destructor should not be pure virtual, just virtual.
virtual ~A() {}
The destructor of B will automatically try to call the destructor of A.
精彩评论