C ++不允许使用=
复制C样式的数组。但是允许使用=
复制结构,如此链接-> Copying array in C v/s copying structure in C。它尚无任何可靠的答案。但是请考虑以下代码
#include <iostream>
using namespace std;
struct user {
int a[4];
char c;
};
int main() {
user a{{1,2,3,4}, 'a'}, b{{4,5,6,7}, 'b'};
a = b; //should have given any error or warning but nothing
return 0;
}
以上代码段未提供任何类型的错误和警告,并且运行正常。为什么?考虑解释两个问题(这个问题和上面链接的一个问题)。
您的班级user
得到一个implicitly declared copy constructor和implicitly declared copy assignment operator。
隐式声明的副本分配运算符将内容从b
复制到a
。
是的,代码应该可以正常工作。 arrays不能直接整体分配;但它们可以由implicity-defined copy assignment operator分配为数据成员,对于非联合类类型,它执行非静态数据成员(包括数组成员及其元素)的逐成员副本分配。
数组类型的对象不能作为一个整体进行修改:即使它们是左值(例如,可以采用数组的地址),它们不能出现在赋值运算符的左侧:
int a[3] = {1, 2, 3}, b[3] = {4, 5, 6}; int (*p)[3] = &a; // okay: address of a can be taken a = b; // error: a is an array struct { int c[3]; } s1, s2 = {3, 4, 5}; s1 = s2; // okay: implicity-defined copy assignment operator // can assign data members of array type