zoukankan      html  css  js  c++  java
  • 继承中的构造析构函数调用顺序

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

      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. 执行父类析构函数

  • 相关阅读:
    maven打包时加入依赖包及加入本地依赖包
    is_file和file_exists效率比较
    window.open()详解及浏览器兼容性问题示例探讨
    Zend Studio汉化失败,如何给Zend Studio进行汉化
    HTML页面跳转的5种方法
    PHP中的符号 ->、=> 和 :: 分别表示什么意思?
    php中$this->是什么意思
    关于define('DISCUZ_ROOT', substr(dirname(__FILE__), 0, -7));的理解
    【精华】PHP网站验证码不显示的终结解决方案
    php提示undefined index的几种解决方法
  • 原文地址:https://www.cnblogs.com/zsy12138/p/10846437.html
Copyright © 2011-2022 走看看