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

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

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      
posted @ 2018-06-04 21:58  小石王  阅读(2075)  评论(0编辑  收藏  举报