【问题标题】:How to initialize the `std::map<std::string, CodeInfo>` using list-initialization?如何使用列表初始化来初始化`std::map<std::string, CodeInfo>`?
【发布时间】:2018-12-10 10:37:34
【问题描述】:

我有一个带有 string 键和一个 struct 值的映射,我不知道为什么我不能使用 a list of initializers 实例化一个对象:

#include <string>
#include <map>    
using namespace std;

struct CodeInfo
{
    int _level = 0;
    bool _reactive;
};
typedef map<string, CodeInfo> CodeInfos; // Key is code name

int main()
{
    CodeInfos codes = { {"BARECODE", { 0, true }}, {"BARECODE2", { 0, false }} };

    return 0;
}

这似乎很简单,但我不明白为什么会出现以下错误:

In function 'int main()':    
24:80: error: could not convert '{{"BARECODE", {0, true}}, {"BARECODE2", {0, false}}}' from '<brace-enclosed initializer list>' to 'CodeInfos {aka std::map<std::basic_string<char>, CodeInfo>}'

我使用编译器 g++ (GCC) 4.9.1 20140922 (Red Hat 4.9.1-10) 和 C++11。

【问题讨论】:

    标签: c++ class c++11 stdmap list-initialization


    【解决方案1】:

    原因是CodeInfo 不是聚合的,因为您在类的定义中直接初始化其中一个数据成员(_level = 0)。

    删除该成员的default initialization 将适用于 C++11。 See here

    阅读这篇文章了解更多关于聚合的信息:What are Aggregates and PODs and how/why are they special?

    【讨论】:

    • "这相当于为类提供默认构造函数,因此不适用于列表初始化。"不,不是。
    • 而且我们通常不会调用int _level = 0;“直接初始化”。该标准使用术语“默认成员初始值设定项”。
    • @cpplearner 感谢您指出正确的词。关于 default constructor ,我在另一个答案中找到了。你能指出我,到底有什么区别。?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-30
    • 2013-09-12
    • 2016-02-06
    • 2016-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多