gpt4 book ai didi

c++:按成员分配是如何工作的?

转载 作者:IT老高 更新时间:2023-10-28 23:18:59 25 4
gpt4 key购买 nike

Possible Duplicate:
How are C array members handled in copy control functions?

如果我不覆盖 operator =一个类,它将使用默认的成员分配。

但这是什么意思?

struct A {
int array[100];
};
A a;
A b=a;

没有错误。 b如何应付aarray ?通常 array_b = array_a无效。

另一个例子:

struct A {
vector<int> vec;
};
A a;
A b=a;

b 怎么样?应付avec ?通过赋值(vec_b = vec_a)、构造函数(vec_b = vector<int>(vec_a))还是其他神秘的方式?

最佳答案

A b=a;

不是赋值,称为 Copy Initialization

调用隐式生成的复制构造函数从现有对象a创建一个新对象b
隐式生成的复制构造函数会复制 array 成员。

为了完整起见,我将在此处添加标记重复的标准引用。

C++03 标准:12.8(复制类对象)

Each subobject is copied in the manner appropriate to its type:

  • if the subobject is of class type, the copy constructor for the class is used;
  • if the subobject is an array, each element is copied, 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/10461518/

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