• 基类和派生类析构函数执行顺序


    转载一片博客:

    http://www.cnblogs.com/dongling/p/5864295.html

    下面是自己实验结果:

    没有声明虚函数时:

    #include <iostream>
    using namespace std;
    
    class Base
    {
    public:
        Base()
        {
            cout<<"Base contruction"<<endl;
        }
         ~Base()
        {
            cout<<"Base deconstruction"<<endl;
        }
    
    };
    
    class Derived: public Base
    {
    public:
        Derived(int i)
        {
            num = i;
            cout<<"Derived contruction "<<num<<endl;
        }
         ~Derived()
        {
            cout<<"Derived deconstruction"<<num<<endl;
        }
    
    };
    
    int main()
    {
        Derived derived(1);
    
        Base* basePtr;
        Derived* derevedPtr;
        
        basePtr = new Derived(2);
        
        delete basePtr;
        
        
    
    
    }

    输出:

    Base contruction
    Derived contruction 1
    Base contruction
    Derived contruction 2
    Base deconstruction
    Derived deconstruction1
    Base deconstruction
    跟上面博文实验结果一致

    总结:
    由上面的实验结果可以看出,当 new CDerive() 时,会先运行基类的构造函数,然后再运行派生类的构造函数;
    而当 delete pointer 时,编译器只考虑 pointer 指针本身的类型而不关心 pointer 实际指向的类型,即:若 pointer 为基类指针,则只调用基类的析构函数(不管 pointer 实际指向的是基类还是派生类);若 pointer 是派生类指针,则先调用派生类的析构函数,再调用基类的析构函数,调用顺序与调用构造函数的顺序相反。

    在声明虚函数之后:

    #include <iostream>
    using namespace std;
    
    class Base
    {
    public:
        Base()
        {
            cout<<"Base contruction"<<endl;
        }
        virtual ~Base()
        {
            cout<<"Base deconstruction"<<endl;
        }
    
    };
    
    class Derived: public Base
    {
    public:
        Derived(int i)
        {
            num = i;
            cout<<"Derived contruction "<<num<<endl;
        }
        virtual ~Derived()
        {
            cout<<"Derived deconstruction"<<num<<endl;
        }
    
    };
    
    int main()
    {
        Derived derived(1);
    
        Base* basePtr;
        Derived* derevedPtr;
        
        basePtr = new Derived(2);
        
        delete basePtr;
        
        
    
    
    }

    输出:

    Base contruction
    Derived contruction 1
    Base contruction
    Derived contruction 2
    Derived deconstruction2
    Base deconstruction
    Derived deconstruction1
    Base deconstruction

  • 相关阅读:
    【Xamarin挖墙脚系列:IOS-关于手机支持的屏幕方向】
    【Xamarin挖墙脚系列:Xamarin 上台讲述PPT呵呵呵】
    Java文件下载
    javaWeb学习总结(2)- http协议
    javaWeb学习总结(1)- JavaWeb开发入门
    java中几种获取项目路径方式
    XSS研究1-来自外部的XSS攻击
    Session Cookie的HttpOnly和secure属性
    关于Cookie安全性设置的那些事
    Hibernate 所有缓存机制详解
  • 原文地址:https://www.cnblogs.com/hong2016/p/6699845.html
Copyright © 2020-2023  润新知