2011-03-05 28 views
4

爲什麼在設置類組合時,包含的類可以使用默認構造函數調用,但不能使用帶參數的類?類的組合

這有點令人困惑;讓我舉個例子。

#include "A.h" 
class B 
{ 
private: 
    A legal; // this kind of composition is allowed 
    A illegal(2,2); // this kind is not. 
}; 

假設默認構造函數和帶有2個整數的構造函數都存在,只允許其中的一個。爲什麼是這樣?

回答

8

這是肯定的,但你只需要寫它不同。您需要使用初始化列表爲複合類的構造函數:

#include "A.h" 

class B 
{ 
private: 
    A legal; // this kind of composition is allowed 
    A illegal; // this kind is, too 
public: 
    B(); 
}; 

B::B() : 
    legal(), // optional, because this is the default 
    illegal(2, 2) // now legal 
{ 
} 
+0

在合法的情況下,A的構造函數被調用。這將爲A調用默認的構造函數3次 – heater 2011-03-05 18:37:38

+0

@heater:我不知道你在說什麼;一個特定對象的構造函數只能通過設計被調用一次。 (除非放置'新',但這可能會帶你進入UB的領域。) – Thomas 2011-03-05 18:38:40

2

可以提供構造函數的參數,但你初始化你的成員是錯誤的。

#include "A.h" 

class B 
{ 
private: 
    int x = 3; // you can't do this, either 
    A a(2,2); 
}; 

這是你的解決方案,ctor-initializer

#include "A.h" 

class B 
{ 
public: 
    B() : x(3), a(2,2) {}; 
private: 
    int x; 
    A a; 
}; 
+0

你打算寫'B()',而不是'A()',對不對? ;) – Thomas 2011-03-05 18:39:42

+0

@Thomas:哎呀,謝謝:) – 2011-03-05 18:56:38

0

類的聲明沒有初始化它組成的類成員。因此,當您嘗試在聲明中構建對象時發生錯誤。

成員初始化發生在類的構造函數內部。所以你應該寫:

#include "A.h" 
class B 
{ 
public: 
    B(); 
private: 
    A a; 
}; 

B::B() : 
    a(2,2) 
{ 
}