使用C ++ 11的成员初始值设定项列表中的初始值设定项列表语法 [英] Initializer list syntax in member initializer list using C++11

查看:289
本文介绍了使用C ++ 11的成员初始值设定项列表中的初始值设定项列表语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在浏览' A C ++浏览',而Bjarne使用c构造函数中的成员初始化中的++ 11初始化程序列表功能,如下所示(使用大括号):

I've been going through 'A Tour of C++' and Bjarne uses the the c++11 initializer list feature in member initialization in a constructor, like so (using curly brackets):

A a;
B b;
Foo(Bar bar):
  a{bar.a}, b{bar.b}
{}

但是,此文件在c ++ 11之前无法编译.与旧成员初始值设定项列表有什么区别(使用圆括号):

This, however doesn't compile prior to c++11. What is the difference with the old member initializer list (using round brackets):

Foo(Bar bar):
  a(bar.a), b(bar.b)
{}

那有什么区别?什么时候应该优先选择另一个?

So what is the difference and when should one be preferred over the other?

推荐答案

那有什么区别?

So what is the difference?

圆括号仅适用于非类类型,或者具有适当构造函数的类型可用于括号中的参数.

Round brackets only work for non-class types, or types with a suitable constructor for the number of arguments in the brackets.

花括号适合这些对象,也适合聚合-简单的struct或没有构造函数的数组类型.因此,以下方法将起作用:

Squiggly braces work for these, and also for aggregates - simple struct or array types with no constructor. So the following will work:

struct {
    int a,b;
} aggregate;
int array[2];

Foo() : aggregate{1,2}, array{3,4} {}

最后,花括号将匹配采用适当类型的initializer_list的构造函数,而不是带有参数的构造函数以匹配参数.例如:

Finally, braces will match a constructor taking a suitably-typed initializer_list, rather than a constructor with parameter(s) to match the arguments. For example:

std::vector<int> v1;
std::vector<int> v2;

Foo() :
    v1(10,2),   // 10 elements with value 2
    v2{10,2}    // 2 elements with value 10,2
{}

何时应该优先选择另一个?

when should one be preferred over the other?

如果希望更清楚地表明初始化是使用构造函数而不是聚合或initializer_list,则最好使用圆括号;或强制使用特定的构造函数.

Prefer round brackets if you want to make it clearer that the initialisation is using a constructor rather than aggregate or initializer_list; or to force use of a specific constructor.

在需要以其他方式不支持的初始化形式时,请使用大括号;或者当您只希望初始化做正确的事"时.

Prefer braces when you need a form of initialisation not otherwise supported; or when you just want the initialisation to "do the right thing".

在两者都做相同事情的情况下,选择主要是出于审美目的.

In the cases where both do the same thing, the choice is largely aesthetic.

这篇关于使用C ++ 11的成员初始值设定项列表中的初始值设定项列表语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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