开发者

c++ struct definition - how to define a member struct with a single argument in its constructor

Simple question. I have a struct which has a member that is also a struct. The member struct takes one string parameter on construction. However, in the class definition, the compiler doesn't allow i开发者_开发知识库t to be instantiated from there. I.e. the following is not allowed:

struct StructName {
   string       str;
   OtherStruct  other_struct("single string param")   
};

So I tried not giving it a parameter which fails because it has to take one:

struct StructName {
   string       str;
   OtherStruct  other_struct;

   StructName(string arg);  
};

I'm new to C/C++ so I'm sorry if it's an idiotic question.

Thanks.


Use an initialization list:

struct StructName {
   string       str;
   OtherStruct  other_struct;

   StructName(): other_struct("init string") { }   
};

You can also take an argument to StructName and pass it along to other_struct, such as:

StructName(string arg): other_struct(arg) { }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜