gpt4 book ai didi

c++ - 为什么在用花括号初始化结构时会出错?

转载 作者:行者123 更新时间:2023-12-01 14:04:19 24 4
gpt4 key购买 nike

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

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}};
}

最佳答案

当您提供 默认构造函数和析构函数,您正在使结构成为 non-aggregate type, hence aggregate initialization不可能。
但是,您可以使用标准 std::is_aggregate_v 检查类型是否为聚合。特征。 (自 起)。
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 ed,当它被认为是 用户声明 用户提供清楚:(积分 @NathanOliver)
    C++ zero initialization - Why is `b` in this program uninitialized, but `a` is initialized?

    关于c++ - 为什么在用花括号初始化结构时会出错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62646128/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com