为什么我在初始化带大括号的结构时出错?
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 以来(。
请参阅此处了解您的情况。它不是聚合,如您提供的那样†这些构造函数。
您可以通过以下三种方式完成此操作:
-
删除构造函数,您就可以开始了。
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
构造函数,何时将其视为用户声明和用户明确提供: (信用@NathanOliver(
C++零初始化 - 为什么此程序中的"b"未初始化,但"a"已初始化?
相关文章:
- 为什么我在初始化带大括号的结构时出错?
- 尝试将指针与结构一起使用时出错
- PCL 出错:体系结构x86_64 @pcl的未定义符号
- 尝试初始化结构内的联合时出错
- 当使用 std::CIN 输入结构时,它会出错
- 在 boost::heap::p riority_queue 中推送结构对象时出错
- 确定输入"conscalc: calc"的类型时出错。不能联合编码器。具有不同字段集的结构类型
- 尝试将数据添加到结构内部的矢量时出错
- 使用提升库在队列和堆栈数据结构上保存和加载数据时出错
- 尝试将结构指针传递给类时出错
- 在旧的 c++ (<c++11) 中,初始化结构会出错
- 类中私有结构的构造函数出错
- 读取结构数组时出错
- 将模板参数传递到内部结构时出错
- 创建局部结构的 std::向量时出错
- 在 C++ 中访问泛型结构的成员会出错
- 使用映射<字符串,结构>类型的映射编译头文件时出错
- 使用单元测试 (cppunit) 中另一个文件中定义的结构时出错
- 初始化作为结构成员的函数指针时出错
- C++中的初始化结构出错