我有一个带字符串键和结构值的映射,我不知道为什么我不能使用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 .
1 回答
原因是
CodeInfo
不是聚合的,因为您是在类的定义中直接初始化其中一个数据成员(_level = 0
) .删除该成员的default initialization将适用于C 11. See here
阅读这篇文章,了解有关聚合的更多信息:What are Aggregates and PODs and how/why are they special?