2015-09-19 89 views
3

我只是想了解它是如何發生的,因爲它是新的C++。將對象初始化爲另一個類的成員

讓我詳細說明我的問題陳述。

class test1 { 
public: 
    test1() { 
     cout << " test1::constructor called" << endl; 
    } 
    ~test1() { 
     cout << " test1::destrcutor called" << endl; 
    } 
}; 

class test2 { 
public: 
    test2() { 
     cout << " test2::constructor called" << endl; 
    } 
    ~test2() { 
     cout << " test2::destrcutor called" << endl; 
    } 
}; 

class derived :public test1, public test2 { 
    test2 t2; 
    test1 t1; 
public: 
    derived() { 
     cout << " derived constructor called" << endl; 
    } 
    ~derived() { 
     cout << "derived destructor called" << endl; 
    } 
}; 

int main() { 
    derived d; 
    return 0; 
} 

上述程序的輸出顯示

test1::constructor called 
    test2::constructor called 
    test2::constructor called 
    test1::constructor called 
    derived constructor called 
    derived destructor called 
    test1::destrcutor called 
    test2::destrcutor called 
    test2::destrcutor called 
    test1::destrcutor called 

所以在這裏我的問題是,在什麼點它叫做成員變量的構造函數在派生類中,因爲我還沒有把任何初始化爲同。

+0

由於您是C++新手,因此使用繼承和多態性時要注意的一件事是確保您從您派生的類正在使用虛擬析構函數,這將爲您節省大量未來的麻煩!由於派生從test1和test2繼承,所以test1和test2中的兩個析構函數都應該是虛擬的!這可能不是必須的,但將派生析構函數虛擬爲好也是一種好的做法!這有助於保持對象被銷燬的順序,以便類中的指針保持有效,特別是在處理動態或新內存時。 –

回答

8

施工的順序是鹼,則成員,以便: -

test1::constructor called << first base of 'derived' 
test2::constructor called << second base of 'derived' 
test2::constructor called << member of 'derived' t2 
test1::constructor called << member of 'derived' t1 
derived constructor called << code in 'derived::derived' 
derived destructor called << code in 'derived::~derived' 
test1::destrcutor called << destruction of t1 
test2::destrcutor called << destruction of t2 
test2::destrcutor called << destruction of derived 
test1::destrcutor called << destruction of derived 

只有一個對象的析構函數,它有一個限定以破壞對象。這是從班級的底部到頂部摧毀所有成員。

然後摧毀這個班級,並且它的基地處於「逆序」。

每個構造函數都可以選擇要初始化的內容,而不是順序。

a_class::a_class(params) : 
      base_n(params), base_n_1(params), 
      member_1(params), member_2(params),... 

member initialization list允許被賦予不同的參數來構建所有的基礎和對象,但不影響秩序。它始終是first_basesecond_base,first_member, second_member,...

這個順序是爲了確保它與析構函數相反。

這些規則允許我確定哪些消息來自成員,哪些來自基地。

未從member initialization list初始化的成員仍將獲得其默認構造函數test2::test2。因爲一旦有一個構造函數,它們只會通過調用一個構造函數而成立。

Plain-old-DataPOD是簡單的類型,如int沒有構造函數。它們沒有初始化(無論內存中的值是什麼)。