使用其他成员初始化结构的成员?
Initializing members of a struct using other members?
我想知道是否可以创建一个结构,并使用结构中初始化的成员/变量作为参数来构建其他成员。例如,我想做一个结构:
struct myStruct {
size_t length;
std::string (&strings)[length]; // from the above variable
};
像这样的东西。我知道初始化顺序有一些微妙之处,但我确信可以解决一些问题(也许是构造函数?目前,我发现唯一有效的方法是模板:
template <size_t N>
struct myStruct {
int length;
std::string (&strings)[N]; // from the template parameter
};
请记住,我实际上将我的length
值作为结构中的成员变量传递,因此理想情况下我不需要模板。
编辑:
澄清:我只需要访问数组字符串并能够从中读取(无需覆盖它们,因此可以而且应该使用const
(,就像使用常规数组一样:基于[]的符号。我也可以容忍对std::array
的更改.无论如何,我只需要字符串易于访问,其方式与常规使用没有明显不同。此外,它必须来自结构指针(也称为箭头运算符(。
多谢!
您不得使用
struct myStruct {
size_t length;
std::string (&strings)[length];
};
因为length
不是编译时常量。
您最好的选择可能是使用std::vector<std::string>&
.
struct myStruct {
// Assuming you were using a reference on purpose.
std::vector<std::string>& strings;
};
并在构造函数中初始化它。
struct myStruct {
myStruct(std::vector<std::string>& in) : strings(in) {}
std::vector<std::string>& strings;
};
如果在编译时知道数组的大小,则有几个选择。
使用常规的
std::string
数组。template <size_t N> struct myStruct { int length; std::string (&strings)[N]; };
使用
std::string
秒的std::array
。template <size_t N> struct myStruct { int length; std::array<std::string, N>& strings; };
第二个选项更好,因为std::array
拥有常规数组拥有的一切以及更多。
相关文章:
- 如何在C++中定义静态成员结构
- 使用模板化类的成员结构
- 初始化固定的 C 数组成员结构
- 指向成员结构的指针如何工作
- 如何将此“指针从外部类传递到成员结构
- 导致IAR ARM中出现错误的成员结构位字段元素的Initializer列表初始化
- 映射文件中成员结构的地址
- Visual C++ 模板类成员结构初始化语法糖
- C :初始化成员结构的静态字段的正确方法
- 如何在C 类的初始化器列表中使用未命名结构初始化成员结构
- 从成员结构的成员函数中访问类的成员?
- 模板化类的成员函数无法返回指向成员结构的指针?
- 重载非类型模板结构的成员结构的复制赋值运算符
- 灵气属性传播问题与单成员结构.
- 将具有 int* 成员C++结构编接到 C#
- 复杂的班级成员结构
- 将向量成员(结构)传递给函数
- 成员结构的前向声明
- 重载运算符<<用于模板结构中定义的成员结构
- 返回带有模板化类的类成员结构