简体   繁体   English

复制 C 风格 arrays 和结构

[英]copying C-style arrays and structure

C++ does not allow copying of C-style arrays using = . C++ 不允许使用=复制 C 样式 arrays。 But allows copying of structures using = , as in this link -> Copying array in C v/s copying structure in C .It does not have any credible answers yet.但是允许使用=复制结构,如在此链接中 -> 在 C 中复制数组与在 C 中复制结构。它还没有任何可靠的答案。 But consider following code但考虑以下代码

#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;
}

Above code segment didn't gave any kind of errors and warnings, and just works fine.上面的代码段没有给出任何错误和警告,并且工作正常。 WHY?为什么? Consider explaining both questions(this one and the one linked above).考虑解释这两个问题(这个和上面链接的一个)。

Your class user gets an implicitly declared copy constructor and implicitly declared copy assignment operator .您的 class user获得了隐式声明的复制构造函数隐式声明的复制赋值运算符

The implicitly declared copy assignment operator copies the content from b to a .隐式声明的复制赋值运算符将内容从b复制到a

Two passages from the standard that seems to apply:标准中似乎适用的两个段落:

class.copy.ctor class.copy.ctor

if the member is an array, each element is direct-initialized with the corresponding subobject of x;如果该成员是一个数组,则每个元素都直接使用 x 的相应子对象进行初始化;

class.copy.assign class.copy.assign

if the subobject is an array, each element is assigned, in the manner appropriate to the element type;如果子对象是数组,则以适合元素类型的方式分配每个元素;

Yes, the code should work fine.是的,代码应该可以正常工作。 arrays can't be assigned directly as a whole; arrays不能直接整体赋值; but they can be assigned as data member by the implicity-defined copy assignment operator , for non-union class type it performs member-wise copy assignment of the non-static data member, including the array member and its elements.但它们可以通过隐式定义的复制分配运算符分配为数据成员,对于非联合 class 类型,它执行非静态数据成员的成员方式复制分配,包括数组成员及其元素。

Objects of array type cannot be modified as a whole: even though they are lvalues (eg an address of array can be taken), they cannot appear on the left hand side of an 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM