什么是通过花括号调用的赋值?并可以控制? [英] What is assignment via curly braces called? and can it be controlled?

查看:167
本文介绍了什么是通过花括号调用的赋值?并可以控制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是什么名字?

Vec3 foo = {1,2,3};

可以通过操作员或其他方式控制吗?

Can it be controlled via an operator or some such? As in can I specify how this should act?

例如,如果我有一些复杂的类,我可以使用这个来分配变量吗?

For instance if I had some complicated class could I use this to assign variables? (Just an exercise in curiosity).

推荐答案

这不是赋值。这是初始化。

That is not assignment. That is initialization.

这样的初始化仅允许用于聚合,包括POD类。 POD表示普通数据类型。

Such initialization is allowed for aggregate only, that includes POD class. POD means Plain Old Data type.

示例,

//this struct is an aggregate (POD class)
struct point3D
{
   int x;
   int y;
   int z;
};

//since point3D is an aggregate, so we can initialize it as
point3D p = {1,2,3};

查看上述编译正确: http://ideone.com/IXcSA

但请再次考虑:

//this struct is NOT an aggregate (non-POD class)
struct vector3D
{
   int x;
   int y;
   int z;
   vector3D(int, int, int){} //user-defined constructor!
};

//since vector3D is NOT an aggregate, so we CANNOT initialize it as
vector3D p = {1,2,3}; //error

上面的不编译。它给出这个错误:

The above does NOT compile. It gives this error:


prog.cpp:15:error:非聚合类型'vector3D'

prog.cpp:15: error: braces around initializer for non-aggregate type ‘vector3D’

查看自己: http://ideone.com/zO58c

point3D vector3D之间有什么区别 ?只是 vector3D 有用户定义的构造函数,它使它非POD。因此,它不能使用花括号来初始化!

What is the difference between point3D and vector3D? Just the vector3D has user-defined constructor, and that makes it non-POD. Hence it cannot be initialized using curly braces!

标准在§8.5.1/ 1节中说明,

The Standard says in section §8.5.1/1,


聚合是数组或类没有用户声明的
构造函数
(12.1),没有私有或
保护非静态数据成员

/ strong>
(第11条),没有基类(子句
10)和没有虚函数(10.3)

An aggregate is an array or a class (clause 9) with no user-declared constructors (12.1), no private or protected non-static data members (clause 11), no base classes (clause 10), and no virtual functions (10.3).

然后它在§8.5.1/ 2中说,

And then it says in §8.5.1/2 that,


初始化聚合时,
初始化程序可以包含
initializer-clause,其中包含
括号括起来的逗号分隔的
初始化子句列表成员
的总计,写成增加
下标或成员的顺序。如果
聚合包含子聚合,则此
规则递归应用于子聚集的
成员。

When an aggregate is initialized the initializer can contain an initializer-clause consisting of a brace-enclosed, comma-separated list of initializer-clauses for the members of the aggregate, written in increasing subscript or member order. If the aggregate contains subaggregates, this rule applies recursively to the members of the subaggregate.



[Example:

struct A 
{
   int x;
   struct B 
   {
      int i;
      int j;
   } b;
} a = { 1, { 2, 3 } };

initializes a.x with 1, a.b.i with 2, a.b.j with 3. ]

这篇关于什么是通过花括号调用的赋值?并可以控制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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