继承时,构造函数和析构函数的调用顺序

继承时,构造函数和析构函数的调用顺序

1. 先调用父类的构造函数,再初始化成员,最后调用自己的构造函数

2.先调用自己的析构函数,再析构成员,最后调用父类的析构函数

3.如果父类定义了有参数的构造函数,则自己也必须自定义带参数的构造函数

4.父类的构造函数必须是参数列表形式的

5.多继承时,class D: public Base2, Base1, Base的含义是:class D: public Base2, private Base1, private Base,而不是class D: public Base2, public Base1, public Base

6.多继承时,调用顺序取决于class D: public Base2, public Base1, public Base的顺序,也就是先调用Base2,再Base1,再Base。但是有虚继承的时候,虚继承的构造函数是最优先被调用的。

include <iostream>
using namespace std;

class Base{
public:
  Base(int d) : x(d){
    cout << "create Base" << endl;
  }
  ~Base(){
    cout << "free Base" << endl;
  }
private:
  int x;
};
class Base1{
public:
  Base1(int d) : y(d){
    cout << "create Base1" << endl;
  }
  ~Base1(){
    cout << "free Base1" << endl;
  }
private:
  int y;
};
class Base2{
public:
  Base2(int d) : z(d){
    cout << "create Base2" << endl;
  }
  ~Base2(){
    cout << "free Base2" << endl;
  }
private:
  int z;
};
class D: **public** Base2, **public** Base1, **public** Base{
public:
  D(int d):Base1(d), Base(d), Base2(d), b(d), b1(d), b2(d){
    //编译不过
    //Base1(d); //父类的构造函数必须是参数列表形式的                                                                     
    cout << "create D" << endl;
  }
  ~D(){
    cout << "free D" << endl;
  }
private:
  Base2 b;
  Base1 b1;
  Base b2;
};
int main(){
  D d(10);
}

执行结果:

create Base2                                                                         
create Base1                                                                         
create Base                                                                          
create Base2                                                                         
create Base1                                                                         
create Base                                                                          
create D                                                                             
free D                                                                               
free Base                                                                            
free Base1                                                                           
free Base2                                                                           
free Base                                                                            
free Base1                                                                           
free Base2      

原文链接: https://www.cnblogs.com/xiaoshiwang/p/9135875.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    继承时,构造函数和析构函数的调用顺序

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/275306

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月15日 上午12:56
下一篇 2023年2月15日 上午12:57

相关推荐