c++结构定义-如何在构造函数中定义具有单个参数的成员结构
c++ struct definition - how to define a member struct with a single argument in its constructor
简单问题。我有一个结构,它有一个成员也是结构。成员结构在构造时接受一个字符串参数。然而,在类定义中,编译器不允许从那里实例化它。即不允许出现以下情况:
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) { }
相关文章:
- 我的超类中的模板问题与结构定义
- 为私有结构定义双参数运算符重载
- 可视化C++中的结构定义错误
- 如何在结构定义中组合__attribute__((dllexport))和[[nodiscard]]?
- COM 互操作结构定义与内存布局不匹配
- C 在标题文件中创建具有结构定义的结构的队列
- 如何将结构定义为结构的成员
- 在这个节点定义中,为什么我们在结构定义之后使用"Node"?
- 不同模块中的ambigus结构定义
- 有条件的C/C 结构定义
- C++ 初始化结构定义中的向量
- 字符串声明中的结构定义中的字符串声明
- 使用结构定义函数
- 为具有许多数据成员的结构定义 == 和<
- enableif结构定义和默认模板参数
- C 使用模板为结构定义别名
- C/C++ 中的套接字编程 - 接收由 typedef 结构定义的消息
- 为C++结构定义显式析构函数如何影响调用约定
- 当结构定义在头文件中时,如何在main()中创建结构数组
- C结构定义标准