C++11 正确的结构初始化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9557464/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 12:59:03  来源:igfitidea点击:

C++11 Proper Structure Initialization

c++c++11

提问by 01100110

Having a structure like this in C++11:

在 C++11 中有这样的结构:

struct von
{
    std::string Name;
    unsigned int ID;
    std::vector<std::string> Checks;
};

Should it be initialized like this:

它应该像这样初始化:

    von v = {"",0,{}};

Or like this:

或者像这样:

    von v = {};

Both ways seem to work, but the compiler warns about -Wmissing-field-initializerson the latter example.

两种方式似乎都有效,但编译器-Wmissing-field-initializers对后一个示例发出警告。

Edit:
Here are my compiler options:

编辑:
这是我的编译器选项:

g++ main.cpp -ansi -Wall -Wextra -Weffc++ -std=c++0x

I'm using g++ (Debian 4.6.2-12) 4.6.2

我正在使用 g++ (Debian 4.6.2-12) 4.6.2

采纳答案by cooky451

This doesn't require initializer_list at all and work perfectly fine with C++03. Edit: (Ok, for the initialization of the vector you need C++11) In a struct or array initialization, all not explicitly given values are zero-initialized, so if that's what you want = {}; will work just fine.

这根本不需要 initializer_list 并且在 C++03 中工作得很好。编辑:(好吧,对于你需要 C++11 的向量的初始化)在结构或数组初始化中,所有没有明确给出的值都是零初始化的,所以如果这就是你想要的 = {}; 会工作得很好。