为什么用花括号初始化结构时出现错误?

时间:2020-06-29 20:23:59

标签: c++ c++11 initialization c++17 curly-braces

我正在使用以下代码并出现错误。我不明白为什么会收到此错误。

prog.cpp: In function ‘int main()’:
prog.cpp:15:44: error: could not convert ‘{"foo", true}’ from 
                       ‘<brace-enclosed initializer list>’ to ‘option’
                       option x[] = {{"foo", true},{"bar", false}};
                                            ^
prog.cpp:15:44: error: could not convert ‘{"bar", false}’ from 
                       ‘<brace-enclosed initializer list>’ o ‘option’

代码

#include <iostream>
#include <string>
 
struct option
{
    option();
    ~option();
 
    std::string s;
    bool b;
};
 
option::option() = default;
option::~option() = default;

int main()
{
    option x[] = {{"foo", true},{"bar", false}};
}

1 个答案:

答案 0 :(得分:6)

提供 作为默认构造函数和析构函数时,您正在将该结构作为 non-aggregate type, hence aggregate initialization < / em>是不可能的。

但是,您可以使用标准的std::is_aggregate_v特征来检查类型是否是聚合。 (自起)。

See here for your case。它不是汇总,因为您提供了 这些构造函数。

您可以通过以下三种方式完成这项工作:


以下文章介绍了何时default版本的构造函数,何时被用户声明的用户提供的清楚:(信用@NathanOliver

C++ zero initialization - Why is `b` in this program uninitialized, but `a` is initialized?