[英]Why am I getting error while initializing a struct with 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}};
}
当您提供†默认构造函数和析构函数时,您使结构成为非聚合类型,因此无法进行聚合初始化。
但是,您可以使用标准std::is_aggregate_v
特征检查类型是否为聚合。 (因为c++17 )。
请参阅此处了解您的情况。 正如您提供的那样,它不是聚合†那些构造函数。
您可以通过以下三种方式来完成这项工作:
删除构造函数,你对 go 很好。
struct option { std::string s; bool b; };
默认结构内的构造函数(即声明† )。
struct option { std::string s; bool b; option() = default; ~option() = default; };
否则,您需要在struct
中提供合适的构造函数。
struct option { std::string mStr; bool mBool; option(std::string str, bool b): mStr{ std::move(str) }, mBool{ b } {} // other constructors... };
†以下帖子解释了构造函数何时被default
编辑,何时被视为用户声明和用户提供的明确:( Credits @NathanOliver )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.