我正在使用以下代码并出现错误。我不明白为什么会收到此错误。
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}};
}
答案 0 :(得分:6)
提供 † 作为默认构造函数和析构函数时,您正在将该结构作为 non-aggregate type, hence aggregate initialization < / em>是不可能的。
但是,您可以使用标准的std::is_aggregate_v
特征来检查类型是否是聚合。 (自c++17起)。
See here for your case。它不是汇总,因为您提供了 † 这些构造函数。
您可以通过以下三种方式完成这项工作:
删除构造函数和you are good to go。
struct option
{
std::string s;
bool b;
};
Default the constructors inside the struct(即声明 † )。
struct option
{
std::string s;
bool b;
option() = default;
~option() = default;
};
否则,您需要provide a suitable constructor in your struct
。
struct option
{
std::string mStr;
bool mBool;
option(std::string str, bool b)
: mStr{ std::move(str) }
, mBool{ b }
{}
// other constructors...
};
† 以下文章介绍了何时default
版本的构造函数,何时被用户声明的和用户提供的清楚:(信用@NathanOliver )
C++ zero initialization - Why is `b` in this program uninitialized, but `a` is initialized?