gpt4 book ai didi

C++ 函数从对象数组返回对象的拷贝。这是默认行为吗?

转载 作者:行者123 更新时间:2023-11-28 00:21:10 24 4
gpt4 key购买 nike

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

有一个类 Location,location 有一个计数器 (int associatedLocations;) 用来计算从那个位置可以直接到达的位置的数量(最初为 0),还有一个例程

setConnectedLocations(int value) 

可以改变 associatedLocations 变量的值。还有另一个例程,它获取 associatedLocations 变量的值

int getAssociatedLocationsCount(){
return associatedLocations;
}

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

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) 是否复制数组中的对象然后返回它?这是默认/预期的行为吗?

最佳答案

Does the function getLocation(int index) makes a copy of the object in the array and then returns it?

是的,对于这样的函数签名,它返回一个拷贝。

is this the default/expected behaviour?

是的,这是预期的行为。如果你想修改数组中的那个对象返回引用:

Location &getLocation(int index);

关于C++ 函数从对象数组返回对象的拷贝。这是默认行为吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27404964/

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