2012-07-23 58 views
2

我有兩個類L1和L2,L2的定義包括L1作爲成員對象。 L1和L2中的每一個都有自己的構造函數。顯然,在實例化L2時,它的構造函數必須調用L1的構造函數 。但是,我不知道如何去做這件事。這是一個(失敗)嘗試 以及伴隨的編譯器錯誤。調用類的成員對象的構造函數

class L1 
{ 
public: 
    L1(int n) 
     { arr1 = new int[n] ; 
     arr2 = new int[n]; } 
private: 
    int* arr1 ; 
    int* arr2 ; 
}; 


class L2 
{ 
public: 
    L2(int m) 
    { in = L1(m) ; 
     out = L1(m) ; } 

private: 
    L1 in ; 
    L1 out; 

}; 

int main(int argc, char *argv[]) 
{ 
    L2 myL2(5) ; 

    return 0; 
} 

的編譯錯誤是:

[~/Desktop]$ g++ -g -Wall test.cpp    (07-23 10:34) 
test.cpp: In constructor ‘L2::L2(int)’: 
test.cpp:21:5: error: no matching function for call to ‘L1::L1()’ 
test.cpp:8:3: note: candidates are: L1::L1(int) 
test.cpp:6:1: note:     L1::L1(const L1&) 
test.cpp:21:5: error: no matching function for call to ‘L1::L1()’ 
test.cpp:8:3: note: candidates are: L1::L1(int) 
test.cpp:6:1: note:     L1::L1(const L1&) 

如何去修復這個代碼?

+0

使用成員初始值設定項。在構造函數體開始之前,它調用':in(),out()'。 – chris 2012-07-23 14:42:08

回答

7

使用初始化列表:

class L2 
{ 
public: 
    L2(int m) : in(m), out(m) //add this 
    { 
    } 

private: 
    L1 in ; 
    L1 out; 

}; 
2

使用構造函數初始化列表,例如:

L2(int m) : in(m), out(m) { } 

決不時,你應該使用初始化使用分配。

相關問題