2015-05-26 62 views
0

我回過頭來寫一些C++,我老實說生鏽了。如果我只是知道如何恰當地說出它,我會感覺到我會迅速回答我的問題,但是我仍然會很感激您的幫助。從構造函數初始化一個結構

sanitycheck.cpp:

#include <string>  
using namespace std; 

typedef struct STR_1 {  
    int val_a, val_b; 

    STR_1 (int a, int b) 
    { val_a = a; val_b = b; }  
} STR_1; 

typedef struct STR_2{  
    string name; 
    STR_1 myStr1; 

    STR_2 (string n, STR_1 s) 
    { name=n; myStr1 = s; } 
} STR_2; 

int main(){ 

    return 0; 
} // end main 

當我試着使用g++ -o sanitycheck ./test/sanitycheck.cpp編譯我得到以下,

./test/sanitytest.cpp: In constructor ‘STR_2::STR_2(std::string, STR_1)’: 
./test/sanitytest.cpp:25:3: error: no matching function for call to ‘STR_1::STR_1()’ 
    { name=name; myStr1 = &s; } 
^
./test/sanitytest.cpp:25:3: note: candidates are: 
./test/sanitytest.cpp:11:3: note: STR_1::STR_1(int*, int*) 
    STR_1 (int *a, int *b) 
^
./test/sanitytest.cpp:11:3: note: candidate expects 2 arguments, 0 provided 
./test/sanitytest.cpp:7:16: note: STR_1::STR_1(const STR_1&) 
typedef struct STR_1 { 
       ^
./test/sanitytest.cpp:7:16: note: candidate expects 1 argument, 0 provided 
./test/sanitytest.cpp:25:23: error: no match for ‘operator=’ (operand types are ‘STR_1’ and ‘STR_1*’) 
    { name=name; myStr1 = &s; } 
        ^
./test/sanitytest.cpp:25:23: note: candidate is: 
./test/sanitytest.cpp:7:16: note: STR_1& STR_1::operator=(const STR_1&) 
typedef struct STR_1 { 
       ^
./test/sanitytest.cpp:7:16: note: no known conversion for argument 1 from ‘STR_1*’ to ‘const STR_1&’ 

有一件事我不是明確的是STR_2需要爲什麼會STR_1 myStr1;首先調用STR_1構造函數?我不能初始化這兩種類型,

int main() 
{ 
    STR_1 bob = STR_1(5,6); 
    STR_2 tom = STR_2('Tom',bob); 
    return 0; 
} 

謝謝!

+0

另一個重複,可能與更有用的答案:http://stackoverflow.com/questions/2685172/g-no-matching-function-call-error – juanchopanza

+1

@juanchopanza http://stackoverflow.com/questions/926752/爲什麼要我更喜歡使用成員初始化列表可能是一個更好的重複,它顯示了他的確切情況 – dwcanillas

+0

@ juanchopanza的答案並沒有真正解決我的問題。 – darkpbj

回答

2

除非是不是已經從評論到OP鏈接清楚:這這裏,

typedef struct STR_2{  
    string name; 
    STR_1 myStr1; 

    STR_2 (string n, STR_1 s) // here the myStr1 default constructor is called 
    { name=name; myStr1 = s; } 
} STR_2; 

要求STR_1是缺省構造的。爲了解決,你必須構造成員STR_1 myStr1;在構造函數的初始化列表:

STR_2 (string n, STR_1 s) : name(n), myStr1(s) {} 

DEMO

這就要求的STR_1,而不是默認的構造函數(自動生成編譯器生成的拷貝構造函數其中通過提供自定義構造函數來抑制)。


另一種選擇是使用指針STR_1

typedef struct STR_2{  
    string name; 
    std::unique_ptr<STR_1> myStr1; 

    STR_2 (string n, STR_1 s) 
    { name=name; myStr1 = std::make_unique<STR_1>(s); } //just for the sake of explanation 
                 //again, this would be better 
                 //done in the initializer list 
} STR_2; 

然而,我將從第一選擇離開只是一個很好的理由。

+0

Thanks @davidhigh!接受回答這個問題,upvoted爲如何/爲什麼它的工作的一個堅實的解釋。 – darkpbj