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

Jon*_*Lee 2 c++ constructor struct initialization parameter-passing

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

struct myStruct {
    size_t length;
    std::string (&strings)[length]; // from the above variable
};
Run Code Online (Sandbox Code Playgroud)

像这样的东西.我理解初始化顺序有一些细微之处,但我确信可以解决一些问题(构造函数可能?)来克服这个问题.目前,我发现有效的唯一方法是模板:

template <size_t N>
struct myStruct {
    int length;
    std::string (&strings)[N]; // from the template parameter
};
Run Code Online (Sandbox Code Playgroud)

请记住,我实际上将我的length值作为结构中的成员变量传递,因此理想情况下我不需要模板.

编辑:
澄清:我只需要访问数组的字符串并且能够从它们读取(不需要覆盖它们,因此const可以并且应该使用),就像使用常规数组一样:基于[]的表示法.我也可以容忍改变std::array.无论如何,我只需要以与常规用法不同的方式轻松访问字符串.此外,它必须来自结构指针(也称为箭头操作符).

非常感谢!

R S*_*ahu 5

你可能不会使用

struct myStruct {
    size_t length;
    std::string (&strings)[length];
};
Run Code Online (Sandbox Code Playgroud)

因为length不是编译时常量.

您最好的选择可能是使用std::vector<std::string>&.

struct myStruct {
    // Assuming you were using a reference on purpose.
    std::vector<std::string>& strings;
};
Run Code Online (Sandbox Code Playgroud)

并在构造函数中初始化它.

struct myStruct {
    myStruct(std::vector<std::string>& in) : strings(in) {}
    std::vector<std::string>& strings;
};
Run Code Online (Sandbox Code Playgroud)

如果在编译时已知数组的大小,则有几种选择.

  1. 使用常规的std::strings 数组.

    template <size_t N>
    struct myStruct {
        int length;
        std::string (&strings)[N];
    };
    
    Run Code Online (Sandbox Code Playgroud)
  2. 使用std::arraystd::string秒.

    template <size_t N>
    struct myStruct {
        int length;
        std::array<std::string, N>& strings;
    };
    
    Run Code Online (Sandbox Code Playgroud)

第二个选项更好,因为std::arrays具有常规数组的所有内容以及更多内容.