请参照原文:http://blog.csdn.net/zhaori/article/details/1700356
//Example: non- virtual destructors for dynamically allocated objects.
#include <iostream>
#include <string.h>
using std::endl;
using std::cout;
class Thing
{
public:
virtual void what_Am_I( ) {cout << "I am a Thing.\n";}
virtual ~Thing(){cout<<"Thing destructor"<<endl;}
};
class Animal : Thing
{
public:
virtual void what_Am_I( ) {cout << "I am an Animal.\n";}
virtual ~Animal(){cout<<"Animal destructor"<<endl;}
};
void main( )
{
Thing *t =new Thing;
Animal*x = new Animal;
for (int i=0; i<2; i++)
{
if(i==0) t->what_Am_I( ) ;
else if(i==1)
x->what_Am_I( ) ;
}
delete t;
delete x;
return ;
}
/*
**********小结***************************************
* 如果基类中没有虚析构函数,则删除派生类对象时
* 不会调用派生类的析构函数,此时也就会造成
* 内存泄漏。
* 另外,创建派生类对象时,会先创建一个基类对象
* 所以delete x 时,也会调用基类的析构函数。
* 解决办法: 将基类的析构函数设置成虚析构函数
*******************************************************
*/