zoukankan      html  css  js  c++  java
  • 析构函数

    //虚析构函数
    #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

  • 相关阅读:
    Thinking in java(八)-正则表达式
    order by与索引
    order by与索引
    004_常量的设置
    008_ajax没有跳转页面的错误
    007_缺少aspactj依赖
    006_为什么我的本机地址是0.0.0.0.0.1
    005_mybatis逆向工程错误
    004_当用数据库账号密码不对时?
    059_SSM——JDK动态代理是怎么回事?它又是怎么运用到了SSM框架中的?
  • 原文地址:https://www.cnblogs.com/wuzhenbo/p/2512088.html
Copyright © 2011-2022 走看看