gcc 4.8.1中的C ++ 11:复制构造函数的列表初始化不起作用 [英] C++11 in gcc 4.8.1: list-initialization for copy constructor doesn't work

查看:74
本文介绍了gcc 4.8.1中的C ++ 11:复制构造函数的列表初始化不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我鼓励这个问题:
如果我有

I encourages with this problem: If I have

class A
{
public:
};
int main()
{
   A a{};
   A b{a};
}

gcc给出:

moves.cc:在函数'int main()'中:
move.cc:15:7:错误:'A'的初始值设定项过多
A b { a};

moves.cc: In function ‘int main()’: moves.cc:15:7: error: too many initializers for ‘A’ A b{a};

但是当我使用A b(a)而不是A b {a}时,所有编译都正确。如果我声明默认构造函数,它也会进行编译。为什么这样起作用?

But when I use A b(a) instead of A b{a} all compiles correctly. And if I declare default constructor it compiles too. Why does it work so?

推荐答案

该类是一个聚合,因此列表初始化将执行聚合初始化,而不会考虑隐式声明的构造函数。

The class is an aggregate, so list-initialisation will perform aggregate initialisation, and won't consider the implicitly-declared constructors.

由于没有数据成员,因此只有一个空列表才是有效的聚合初始化程序。

Since there are no data members, only an empty list can be a valid aggregate initialiser.


但是当我使用 A b(a)而不是 A b {a} 全部正确编译。

But when I use A b(a) instead of A b{a} all compiles correctly.

直接初始化将使用隐式构造函数,而不是尝试进行聚合初始化。

Direct initialisation will use the implicit constructor rather than attempting aggregate initialisation.


如果我声明默认构造函数,它也可以编译。

And if I declare default constructor it compiles too.

声明构造函数,该类不再是聚合,只能使用构造函数进行初始化。

By declaring a constructor, the class is no longer an aggregate, and can only be initialised using a constructor.

这篇关于gcc 4.8.1中的C ++ 11:复制构造函数的列表初始化不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆