c++结构定义-如何在构造函数中定义具有单个参数的成员结构

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

本文关键字:结构 定义 单个 参数 成员 构造函数 c++      更新时间:2023-10-16

简单问题。我有一个结构,它有一个成员也是结构。成员结构在构造时接受一个字符串参数。然而,在类定义中,编译器不允许从那里实例化它。即不允许出现以下情况:

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

所以我试着不给它一个失败的参数,因为它必须取一个:

struct StructName {
   string       str;
   OtherStruct  other_struct;
   StructName(string arg);  
};

我是C/C++的新手,所以如果这是一个愚蠢的问题,我很抱歉。

谢谢。

使用初始化列表:

struct StructName {
   string       str;
   OtherStruct  other_struct;
   StructName(): other_struct("init string") { }   
};

您还可以将一个参数传递给StructName并将其传递给other_struct,例如:

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