C++函数从对象数组返回对象的副本.这是默认行为吗?

C++ function returning copy of the object from an array of objects. Is this the default behaviour?

本文关键字:对象 默认 副本 函数 数组 返回 C++      更新时间:2023-10-16

我正在编写的程序变得非常复杂,因此我无法提供实际代码,但以下是确切的情况

有一个类,位置,位置有一个计数器(int associatedLocations;),用于计算可以从该位置直接到达的位置数(最初为 0(,以及一个例程

setConnectedLocations(int value) 

可以更改关联位置变量的值。也是另一个获取变量值associatedLocations例程

int getAssociatedLocationsCount(){
    return associatedLocations;
}

在主函数中,我有一个这样的位置数组。

Location locations[5];

也是一个函数,它根据作为参数传递给函数的索引从数组返回位置

Location getLocation(int index){
    return(locations[index]);
}

现在,当我尝试做这样的事情时

getLocation(0).setAssociatedLocations(5);
cout<<getLocation(0).getAssociatedLocationCount();

输出为 0。

即使在做这样的事情locations[0].getAssoicatedLocationCount();输出为 0;

但是当我这样做时

locations[0].setAssociatedLocations(5);
cout<<locations[0].getAssociatedLocationCount();

输出为 5,这是必需的。

函数是否getLocation(int index)在数组中创建对象的副本,然后返回它? 这是默认/预期行为吗?

函数 getLocation(int index( 是否在数组中复制对象,然后返回它?

是的,使用这样的函数签名,它会返回一个副本。

这是默认/预期行为吗?

是的,这是预期行为。如果要改为修改数组返回引用中的该对象:

Location &getLocation(int index);