简体   繁体   中英

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 it to be instantiated from there. Ie 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) { }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM