C++構造一個類的對象的一般順序

#include <iostream>
using namespace std;
class Base0                    // 基類Base0的聲明
{
     public:
          Base0(int y)     { x=y; cout<<"x of Base0: "<<x<<endl;}
          int x;

};
class Base1 : virtual public Base0     // Base0爲虛基類,公有派生Base1類
{
     public:
          Base1(int y):Base0(y)    { cout<<"x of Base1: "<<x<<endl;}
};

class Base2 : virtual public Base0     // Base0爲虛基類,公有派生Base2類
{
     public:
          Base2(int y):Base0(y)    { cout<<"x of Base2: "<<x<<endl;}
};

class Child : public Base1, public Base2
{
     public:
          Child(int y,int u,int v,int w,int m,int n):Base0(y),Base1(y),Base2(y),B2(w),B0(u),B1(v),m(m),n(n){ cout<<"x m n of Child: "<<x<<" "<<m<<" "<<n<<endl;}
          Base0 B0;
          Base1 B1;
          Base2 B2;
          int m;
          int n;
};
int main()
{
      Child child(1,2,3,4,5,6);

      return 0;
}

在這裏插入圖片描述
由結果可知構造對象child 的順序爲:
1.執行虛基類的構造函數
2.按繼承列表次序執行非虛基類構造函數(不再執行虛基類的構造函數)
3.按定義順序進行派生類新增成員對象初始化(若新增對象未出現在初始化列表中,執行默認構造函數)
4.基本數據類型初始化
5.執行函數體

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章