为什么我在初始化带大括号的结构时出错?

Why am I getting error while initializing a struct with curly braces?

本文关键字:结构 出错 初始化 为什么      更新时间:2023-10-16

我正在使用下面的代码并得到错误。我不明白为什么我会收到此错误。

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"已初始化?