本文介绍了在哪里可以使用列表初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题已经涵盖了什么POD和聚合,并提供了一些聚合初始化的例子。

This question already covers what PODs and aggregates are, and provides some examples on aggregate initialization.

这里的问题是在哪里可以使用列表初始化

strong>您可以在哪里使用(缺少更好的字词)列表分配

Also where can you use (in lack of a better term) list assignment?

答案应该同时处理C ++ 03和C ++ 11,突出它们之间的差异。

An answer should deal with both C++03 and C++11, highlighting the differences between them.

推荐答案

C ++ 03



列表初始化



在C ++ 03中,你只能使用列表初始化的聚合(C ++ 03 [dcl.init。 aggr])和标量(C ++ 03 [dcl.init] / 13)类型:

C++03

List initialization

In C++03 you can only use list-initialization for aggregates (C++03 [dcl.init.aggr]) and scalar (C++03 [dcl.init]/13) types:

 > braced-init-list 可以通过合适的构造函数隐式转换为运算符的参数类型,例如 
  • when assigning to a scalar type, if the braced-init-list has a single element that is convertible (without narrowing) to the variable's type (see [expr.ass]/9)
  • when the left operand of the assignment is a class type with a user-defined assignment operator, in which case the braced-init-list is used to initialize the argument of the operator (see [expr.ass]/9). This includes both cases like operator=(std::initializer_list<T>) where the elements of the braced-init-list in the right operand are convertible to T, e.g. for the std::vector<int> v above, v = { 1, 2, 3 } will replace the container's contents with [1,2,3] and when the braced-init-list can be implicitly-converted to the operator's argument type, via a suitable constructor e.g.

code> struct A {
int i;
int j;
};

struct A { int i; int j; };

struct B {
  B& operator=(const A&);
};

int main() {
  B b;
  b = { 0, 1 };
}

在 main 的最后一行

上的
将被隐式转换为临时 A ,那么 B 的赋值运算符将以该临时变量作为其参数来调用。

On the last line of main the braced-init-list will be implicitly-converted to a temporary A then the assignment operator of B will be called with that temporary as its argument.

这篇关于在哪里可以使用列表初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!