2015-05-26 58 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