析构函数

//虚析构函数
#include <iostream>
using std::cout;
using std::endl;

class Base
{
public:
       Base() 
       {
              cout << "Base constructed!" << endl;          //基类构造函数 
       }
       ~Base()
       {
              cout << "Base destructed" << endl;            //基类析构函数 
       } 
};

class Deliver1:public Base
{
public:
       Deliver1()
       {
                 cout << "Deliver1 constructed! " << endl;  //派生类1析构函数        
       }
       ~Deliver1()
       {
                  cout << "Deliver1 destructed!" << endl;   //派生类1析构函数 
       } 
};

class Deliver2:public Deliver1
{
public:
       Deliver2() 
       {
                  cout << "Deliver2 constructed!" << endl;  //派生类2构造函数 
       } 
       ~Deliver2()
       {
                  cout << "Deliver2 destructed!" << endl;   //派生类2析构函数 
       } 
};

int main()
{
    //Deliver2 D;
    Base *D = new Deliver2();
    delete D;
    system("pause");
    return 0;
} 

运行结果:

发现只调用了基类的虚构函数,子类的都没有释放。

于是就有了析过函数,使用析构函数:

//虚析构函数
#include <iostream>
using std::cout;
using std::endl;

class Base
{
public:
       Base() 
       {
              cout << "Base constructed!" << endl;          //基类构造函数 
       }
       virtual ~Base()
       {
              cout << "Base destructed" << endl;            //基类析构函数 
       } 
};

class Deliver1:public Base
{
public:
       Deliver1()
       {
                 cout << "Deliver1 constructed! " << endl;  //派生类1析构函数        
       }
       virtual ~Deliver1()
       {
                  cout << "Deliver1 destructed!" << endl;   //派生类1析构函数 
       } 
};

class Deliver2:public Deliver1
{
public:
       Deliver2() 
       {
                  cout << "Deliver2 constructed!" << endl;  //派生类2构造函数 
       } 
       virtual ~Deliver2()
       {
                  cout << "Deliver2 destructed!" << endl;   //派生类2析构函数 
       } 
};

int main()
{
    //Deliver2 D;
    Base *D = new Deliver2();
    delete D;
    system("pause");
    return 0;
} 

参考文章:http://www.cnblogs.com/justin-wong/archive/2010/01/27/1657521.html

posted @ 2012-05-21 19:22  waynewuzhenbo  阅读(251)  评论(0编辑  收藏  举报