構造順序與析構順序

派生類構造函數執行的次序:

1. 調用基類構造函數,調用順序按照它們 被繼承時聲明的順序 (從左到右);

2. 調用內嵌成員對象的構造函數,調用順序按照它們在類中聲明的順序;

3. 派生類自己構造函數體中的內容。

派生類析構函數執行的次序:

派生類的析構函數的功能是在該對象消亡之前進行一些必要的清理工作,析構函數沒有類型,也沒有參數。

析構函數的執行順序與構造函數相反。


#include <iostream>
using namespace std;
// 基類 B1
class B1
{
public:
    B1(int i)
    {
        cout<<"constructing B1 "<<i<<endl;
    }
    ~B1()
    {
        cout<<"destructing B1"<<endl;
    }
};

//基類 B2
class B2
{
public:
    B2(int j)
    {
        cout<<"constructing B2 "<<j<<endl;
    }
     ~B2()
    {
        cout<<"destructing B2"<<endl;
    }
};

//基類 B3
class B3
{
public:
    B3()
    {
        cout<<"constructing B3"<<endl;
    }
    ~B3()
    {
        cout<<"destructing B3"<<endl;
    }
};

//派生類 C, 繼承B2, B1,B3(聲明順序從左至右。 B2->B1->B3)
class C: public B2, public B1, public B3
{
public:
    C(int a, int b, int c, int d):B1(a), memberB2(d), memberB1(c),B2(b)
    {
		//B1,B2的構造函數有參數,B3的構造函數無參數
      	//memberB2(d), memberB1(c)是派生類對自己的數據成員進行初始化的過程、
        //構造函數執行順序, 基類(聲明順序)-> 內嵌成員對象的構造函數(聲明順序) -> 派生類構造函數中的內容
        C()
        {
            cout<<"constructing C"<<endl;
        }
        ~C()
        {
            cout<<"destructing C"<<endl;
        }
    }
private:
    B1 memberB1;
    B2 memberB2;
    B3 memberB3;
};

int main() 
{ 
    C obj(1,2,3,4);
    return 0; 
}

/* 輸出結果 */
/*
constructing B2 2
constructing B1 1
constructing B3
constructing B1 3
constructing B2 4
constructing B3
constructing C
destructing C
destructing B3
destructing B2
destructing B1
destructing B3
destructing B1
destructing B2
*/

 

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