//正确使用虚析构函数 //使用虚析构函数,当delete删除一个对象时,能确保析构函数正确执行(动态) #include <iostream> using namespace std; class B { public: B() { cout<<"B"<<endl; } virtual void fun() { cout<<"B::fun()"<<endl; } virtual ~B() // ~B() //若非虚析构函数,则会导致子类无法析构 { cout<<"~B"<<endl; } private: int x; }; class D : public B { public: D() { cout<<"D"<<endl; } void fun() { cout<<"D::fun(int)"<<endl; } void show() { cout<<"D::show()"<<endl; } ~D() { cout<<"~D"<<endl; } private: int y; }; void main() { B *pb = new D; delete pb; } <img src="http://img.blog.csdn.net/20150512213756982?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvZG91ZG91d2ExMjM0/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />
原文地址:http://blog.csdn.net/doudouwa1234/article/details/45675421