gpt4 book ai didi

C++默认赋值运算符

转载 作者:可可西里 更新时间:2023-11-01 18:37:52 25 4
gpt4 key购买 nike

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

//

struct test {
int a[10];
};

test a,b;
a = b;

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

最佳答案

来自 C++11 草案,第 12.8 节:

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:

— 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.

这里的重要部分是:如果子对象是数组,则以适合元素类型的方式分配每个元素;

关于C++默认赋值运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18119355/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com