c++ - 不能在两个重叠的结构上使用初始化列表

标签 c++ c++11 initialization list-initialization

我想使用初始化列表来初始化变量 p1 以简化我的操作。但它没有发生请帮助。代码几乎是 self 解释的。

struct word_t {
    int in;
    string word;
    int out;
    word_t(int i, string w, int o): in(i),word(w),out(o) {}
};


struct para_t {
    std::vector<word_t> words;
};

struct song_t { 
    std::vector<para_t> paras;
};    

int main()
{
    //SONG
    std::vector<song_t> song;

    para_t p1{ { 0, "We", 10 }, { 11, "are", 14 } , { 15, "the", 18 } 
    , { 19, "World", 22 } }; // CANNOT INITIALIZE LIKE SO 

    p1.words.push_back(word_t(0, "World", 10));   // THIS WORKS


}

最佳答案

您还需要一个{},即

para_t p1{ { { 0, "We", 10 }, { 11, "are", 14 } , { 15, "the", 18 } , { 19, "World", 22 } } };
//       ^                                                                                  ^ <- for para_t
//         ^                                                                              ^   <- for para_t::words
//           ^             ^                                                                  <- for elements (i.e. word_t) in vector

关于c++ - 不能在两个重叠的结构上使用初始化列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67949203/

相关文章:

c++ - vector::大小和段错误

c++ - 另一个 vector 与动态分配的数组

c++ - 如何在 C++ 中正确返回模板化对象?

c++ - 初始化我的数组时出错

arrays - 在 C 中初始化了一个指针数组 - 可能无法初始化可变大小的对象

c++ - 用 double 计算 pow 会给出错误的结果

c++ - 使用 assign() 是初始化我的 C++ 结构 vector 的好方法吗?

c++ - 使用 C++11 编译后模板函数损坏

c++ - 由于运算符重载,我可以用 '=' 初始化 std::vector 吗?

c++ - 如何在烤宽面条中打印隐藏层的输出