基类的析构函数需要virtual,如果不是virtual 那么delete时将不会调用派生类的析构函数(可能会存在内存泄露)

如下:

class A
 {
 public:
~A()
{
cout << "destroy A\n";
}
 };
 class B:public A
 {
 public:
~B()
{
cout << "destroy B\n";
}
 };
 int _tmain(int argc, _TCHAR* argv[])
 {
A *a=new B;
delete a;
cin.get();
return 0;
 }

输出:destroy A


加上virtual
class A
 {
 public:
virtual ~A()
{
cout << "destroy A\n";
}
 };
 class B:public A
 {
 public:
~B()
{
cout << "destroy B\n";
}
 };
 int _tmain(int argc, _TCHAR* argv[])
 {
A *a=new B;
delete a;
cin.get();
return 0;
 }

输出:

destroy B

destroy A