【问题标题】:Initializing a struct with aggregate initialization and member initializers [duplicate]使用聚合初始化和成员初始化器初始化结构[重复]
【发布时间】:2016-06-23 19:21:36
【问题描述】:

考虑以下示例:

#include <iostream>
#include <string>
struct ABC
{
    std::string str;
    unsigned int id ;/* = 0 : error: no matching constructor for initialization of 'ABC'*/
};

int main()
{
    ABC abc{"hi", 0};
    std::cout << abc.str << " " << abc.id <<   std::endl;
    return 0;
}

在为 id clang 3.x 和 gcc 4.8.x 定义没有默认值的结构 ABC 时,编译代码没有问题。但是,在为“id”添加默认参数后,我得到了流动的错误消息:

13 : error: no matching constructor for initialization of 'ABC'
ABC abc{"hi", 0};
^ ~~~~~~~~~
4 : note: candidate constructor (the implicit copy constructor) not viable: requires 1 argument, but 2 were provided
struct ABC
^
4 : note: candidate constructor (the implicit move constructor) not viable: requires 1 argument, but 2 were provided
4 : note: candidate constructor (the implicit default constructor) not viable: requires 0 arguments, but 2 were provided
1 error generated.
Compilation failed

从技术角度来看,当我使用默认参数定义 id 时会发生什么,为什么在这种情况下无法进行聚合初始化?我是否隐式定义了某种构造函数?

【问题讨论】:

  • 也许我误解了你的问题。 this 是你想要的吗?
  • @erip 这很有趣。它无法在 VS 2015 中编译。
  • 刚刚发现这个thread 与 VS 2015 有关。看起来它可能与您的编译器相同。
  • @user3472628:原因见我的回答。

标签: c++ c++11 constructor aggregate-initialization


【解决方案1】:

Bjarne Stroustrup 和 Richard Smith 提出了一个关于聚合初始化和成员初始化器不能一起工作的问题。

C++11 & C++14 标准对聚合的定义略有改动。

来自 C++11 标准草案n3337 8.5.1 节说:

聚合是没有用户提供的数组或类(第 9 条) 构造函数 (12.1),非静态没有大括号或等号初始化器 数据成员 (9.2),没有私有或受保护的非静态数据成员 (第 11 条),没有基类(第 10 条),没有虚函数 (10.3)。

但是 C++14 标准草案 n3797 第 8.5.1 节说:

聚合是没有用户提供的数组或类(第 9 条) 构造函数(12.1),没有私有或受保护的非静态数据成员 (第 11 条),没有基类(第 10 条),没有虚函数 (10.3)。

因此,当您在 C++11 中为数据成员 id 使用类成员初始化程序(即相等初始化程序)时,它不再保持聚合,您不能写 ABC abc{"hi", 0}; 来初始化 struct ABC. 因为在那之后它不再保持聚合类型。但是您的代码在 C++14 中有效。 (见现场演示here)。

【讨论】:

【解决方案2】:

在 c++ 中,结构和类是相同的,只是结构具有默认的公共成员而类具有私有成员。如果你想使用初始值,我认为你必须编写一个构造函数或使用类似这样的东西:

struct ABC
{
    std::string str;
    unsigned int id;
} ABC_default = {"init", 0 }; //initial values

int main()
{
    ABC abc = ABC_default;
    std::cout << abc.str << " " << abc.id << std::endl;
    return 0;
}

【讨论】:

  • 我真的不认为这回答了 OP 的问题。
  • 这也是错误的,因为 NSDMI 是五年前添加到该语言中的。类似 C 的语法也无助于答案。并且听起来不像是破唱片或任何东西,但“结构和类”并不“相同”; struct 引入了一个 class 结构不存在!
  • 说“结构和类是一样的”是指它们是同类,只是关键字不同。感谢回复
  • 这真的很不灵活。有人想多次初始化 ABC 是什么?他是否必须不断地在 ABC 的定义中指定一种新的 ABC 类型?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-09-25
  • 1970-01-01
  • 1970-01-01
  • 2020-10-22
  • 2020-03-18
  • 2020-08-10
  • 1970-01-01
相关资源
最近更新 更多