使用其他成员初始化结构的成员?

Initializing members of a struct using other members?

本文关键字:成员 结构 初始化 其他      更新时间:2023-10-16

我想知道是否可以创建一个结构,并使用结构中初始化的成员/变量作为参数来构建其他成员。例如,我想做一个结构:

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;
};

如果在编译时知道数组的大小,则有几个选择。

  1. 使用常规的std::string数组。

    template <size_t N>
    struct myStruct {
    int length;
    std::string (&strings)[N];
    };
    
  2. 使用std::string秒的std::array

    template <size_t N>
    struct myStruct {
    int length;
    std::array<std::string, N>& strings;
    };
    

第二个选项更好,因为std::array拥有常规数组拥有的一切以及更多。