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

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值