将对象分配给 C++ 数组

Assigning an object to C++ array

我正在检查以下 C++ 代码:


#include <iostream>

using namespace std;

class Person{
    public:
    int age;
    Person(int age){
        this->age = age;
    }
};

int main()
{
    Person a = Person(2);
    Person temp[] = {a};
    temp[0].age = 5;
    cout << temp[0].age;
    return 0;
}

所以我的猜测是,当在 C++ 中将对象分配给数组的槽时,相当于将该对象复制到数组中。

因此,当我们更改数组中的那个元素时,它不会影响原始对象。对吗?

Person temp[] = {a};不是赋值,而是初始化(aggregate initialization):

Each direct public base, (since C++17) array element, or non-static class member, in order of array subscript/appearance in the class definition, is copy-initialized from the corresponding clause of the initializer list.

所以 temp 被初始化为包含 1 个元素,它是通过 Person 的复制构造函数从 a 复制初始化的。

when we change that element in the array, it will not affect the original object. Is that correct?

是的。


顺便说一句:temp[0] = a; 是赋值; temp[0] 是通过 Person 的复制赋值运算符从 a 复制赋值的。