1. 程式人生 > >C++筆記 第二十一課 物件的構造順序---狄泰學院

C++筆記 第二十一課 物件的構造順序---狄泰學院

如果在閱讀過程中發現有錯誤,望評論指正,希望大家一起學習,一起進步。
學習C++編譯環境:Linux

第二十一課 物件的構造順序

問題:C++中的類可以定義多個物件,那麼物件構造的順序是怎樣的?

1.物件的構造順序一

對於 區域性物件
當程式執行流到達物件的定義語句時進行構造,物件定義->構造
下面程式中的物件構造順序是什麼?
在這裡插入圖片描述

21-1 區域性物件的構造順序

#include <stdio.h>
class Test
{
private:
    int mi;
public:
    Test(int i)
    {
        mi = i;
        printf("Test(int i): %d\n", mi);
    }
    Test(const Test& obj)
    {
        mi = obj.mi;
        printf("Test(const Test& obj): %d\n", mi);
    }
};
int main()
{
    int i = 0;
    Test a1 = i; //Test(int i):0
        
    while( i < 3 )
    {
        Test a2 = ++i; //Test(int i):1,2,3
    }
  //goto End;     
    if( i < 4 )
    {
        Test a = a1; //Test(const Test& obj):0
    }
    else
    {
        Test a(100);
    }
//End: //此時不會輸出最後一個輸出結果
    return 0;
}
執行結果
Test(int i): 0
Test(int i): 1
Test(int i): 2
Test(int i): 3
Test(const Test& obj): 0

2.物件的構造順序二

對於 堆物件
當程式執行流到達new語句時建立物件
使用new建立物件將自動觸發建構函式的呼叫
下面程式中的物件構造順序是什麼?
在這裡插入圖片描述

21-2 堆物件的構造順序

#include <stdio.h>
class Test
{
private:
    int mi;
public:
    Test(int i)
    {
        mi = i;
        printf("Test(int i): %d\n", mi);
    }
    Test(const Test& obj)
    {
        mi = obj.mi;
        printf("Test(const Test& obj): %d\n", mi);
    }
    int getMi()
    {
        return mi;
    }
};
int main()
{
    int i = 0;
    Test* a1 = new Test(i); // Test(int i): 0
        
    while( ++i < 10 )
        if( i % 2 )
            new Test(i); // Test(int i): 1, 3, 5, 7, 9
        
    if( i < 4 )
        new Test(*a1);
    else
        new Test(100); // Test(int i): 100
        
    return 0;
}
執行結果
Test(int i): 0
Test(int i): 1
Test(int i): 3
Test(int i): 5
Test(int i): 7
Test(int i): 9
Test(int i): 100

3.物件的構造順序三

[email protected]:~/c++/21-3$ g++ 21-3.cpp t2.cpp t1.cpp t3.cpp -o test.out
[email protected]:~/c++/21-3$ ./test.out
t4
t2
t1
t3
t5
對於 全域性物件
物件的構造順序是不確定的
不同的編譯器使用不同的規則確定構造順序

21-3 全域性物件的構造順序

小結
區域性物件的構造順序依賴於程式的執行流
堆物件的構造順序依賴於new的使用順序
全域性物件的構造順序是不確定的