c++ - 如何使用初始化列表 C++ 初始化数组

标签 c++ arrays struct initialization

我有一个与 C++ 数组和结构相关的问题。我有一个结构:

struct npc_next_best_spot{
    npc_next_best_spot(): x({0}),
                          y({0}),
                          value(-1),
                          k(0),
                          i({0}), 
                          triple_ress({0}),
                          triple_number({0}),
                          bigI(0)
    {}

    int x[3]; 
    int y[3]; 
    double value; 
    int k; 
    int i[3]; 
    int triple_ress[3]; 
    int triple_number[3];
    int bigI;
};

但这给出了警告

"list-initializer for non-class type must not be parenthesized".

那么我怎样才能确保这些数组都用 0 值初始化呢?

最佳答案

您可以按照错误提示进行操作。您可以为您的数组使用大括号初始值设定项,例如

npc_next_best_spot() : x{}, y{}, value(-1), k(0), i{}, triple_ress{}, triple_number{}, bigI(0) {}

将列表留空是因为任何缺少的初始化器都会对数组中的元素进行零初始化。

关于c++ - 如何使用初始化列表 C++ 初始化数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44500501/

相关文章:

c++ - 如何在数组 <bool> 上使用位操作

ios - 仅当对象不存在时如何将对象添加到数组

c++ - 在C++11中初始化结构体数组

c - 嵌套结构数组

pointers - 将结构转换为 byte slice 的特定地址

c++ - 用自己的 ROI (opencv) 正确替换 cv::Mat

c++ - OpenGL 3D 旋转看起来不像预期的那样

c++ - 结合基于异常和错误代码的类实现

javascript - 为什么下面的原型(prototype)声明不起作用?

c++ - Code::Blocks 中的 MinGW 未链接静态 OpenSSL 库