C ++默认赋值运算符 [英] c++ default assignment operator

查看:303
本文介绍了C ++默认赋值运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int a[10];
int b[10];
a = b;

//

struct test {
    int a[10];
};

test a,b;
a = b;

第一个代码无法编译,因为我们无法分配数组,但是第二个代码可以编译.类的默认赋值运算符不是简单地为每个数据成员调用赋值吗?为什么第二个代码会编译?

First code doesn't compile, since we cant assign array, but the second does. Isn't the default assignment operator of class simply call assignment for each data members? Why does the the second code compile?

推荐答案

摘自C ++ 11草案第12.8节:

From the C++11 draft, section 12.8:

非联盟类X的隐式定义的复制/移动分配操作符对其子对象执行成员式复制/移动分配. X的直接基类首先按照它们在base-specifier-list中的声明顺序进行分配,然后按在类定义中声明的顺序分配X的直接非静态数据成员. .令x为函数的参数,或者对于move运算符,为引用该参数的xvalue.每个子对象都按照适合其类型的方式分配:

The implicitly-defined copy/move assignment operator for a non-union class X performs memberwise copy/move assignment of its subobjects. The direct base classes of X are assigned first, in the order of their declaration in the base-specifier-list, and then the immediate non-static data members of X are assigned, in the order in which they were declared in the class definition. Let x be either the parameter of the function or, for the move operator, an xvalue referring to the parameter. Each subobject is assigned in the manner appropriate to its type:

-如果子对象是类类型,则好像是通过调用operator =将子对象作为对象表达式并将x的相应子对象作为单个函数参数(就像通过显式限定;即忽略任何更多派生类中可能的虚拟覆盖功能);

— if the subobject is of class type, as if by a call to operator= with the subobject as the object expression and the corresponding subobject of x as a single function argument (as if by explicit qualification; that is, ignoring any possible virtual overriding functions in more derived classes);

-如果子对象是数组,则以适合元素类型的方式分配每个元素;

— if the subobject is an array, each element is assigned, in the manner appropriate to the element type;

-如果子对象是标量类型,则使用内置的赋值运算符.

— if the subobject is of scalar type, the built-in assignment operator is used.

这里的重要部分是:if the subobject is an array, each element is assigned, in the manner appropriate to the element type;

这篇关于C ++默认赋值运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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