• 继承中的构造析构函数调用顺序


    子类构造函数必须对继承的成员进行初始化:

      1. 通过初始化列表或则赋值的方式进行初始化(子类无法访问父类私有成员)

      2. 调用父类构造函数进行初始化

        2.1  隐式调用:子类在被创建时自动调用父类构造函数(只能调用父类的无参构造函数和使用默认参数的构造函数)

        2.2  显示调用:在含参构造函数的初始化列表调用父类构造函数(适用所有的父类构造函数)

    #include <iostream>
    #include <string>
    
    using namespace std;
    
    class PParent                //父父类
    {
    public:
        PParent(string s)
        {
            cout << "PParent" << s << endl;
        }
        ~PParent()
        {
            cout << "~PParent" << s << endl;
        }
    };
    
    class Parent : public PParent  // 父类
    {
    public:
        Parent() : PParent("Default")  
        {
            cout << "Parent" << endl;
        }
        Parent(string s) : PParent(s)
        {
            cout << "Parent" << s << endl;
        }
        ~Parent() 
        {
            cout << "~Parent" << endl;
        }
    };
    
    class sib_child              // 同级类
    {
    public:
        sib_child() 
        {
            cout << "sib_child" << endl;
        }
        sib_child(string s)
        {
            cout << "sib_child" << s << endl;
        }
        ~sib_child() 
        {
            cout << "~sib_child" << endl;
        }    
    };
    
    class Child : public Parent    // 自己
    {
        Parent p;
        sib_child sc;
    public:
        Child() : Parent(s),sib_child(s)
        {
            cout << "Child" << endl;
        }
        Child(string s) : Parent(s), sib_child(s) // 先调用父类构造函数,再调用同类构造函数
        {
            cout << "Child" << s << endl;
        }
        ~Child() 
        {
            cout << "~Child" << endl;
        }
    };
    
    int main()
    {       
        Child cc("call : ");
        // 构造顺序
        // PParent   : call         父父类
        // Parent    : call          父类
        // sib_child : call         同类
        // Child     : call            自己
    
        return 0;
        // 析构顺序
        // ~Child     : call            自己
        // ~sib_child : call         同类
        // ~Parent    : call          父类
        // ~PParent   : call         父父类
    }

    构造函数调用顺序:

      1. 执行父类构造函数

      2. 执行同级构造函数

      3. 执行自己构造函数

    析构函数调用顺序:

      1. 执行自己析构函数

      2. 执行同级析构函数

      3. 执行父类析构函数

  • 相关阅读:
    [codevs 1243][网络提速(最短路分层思想)
    [codevs 1183][泥泞的道路(二分+spfa)
    [codevs 2488]绿豆蛙的归宿(拓扑排序)
    [codevs 1961]躲避大龙(dfs)
    4、userCF和itemCF对比,冷启动
    query简洁弹出层代码
    css 积累1
    localStorage,sessionStorage
    tr th td
    (转存)面向切面编程(AOP)的理解
  • 原文地址:https://www.cnblogs.com/zsy12138/p/10846437.html
Copyright © 2020-2023  润新知