C++函数从对象数组返回对象的副本.这是默认行为吗?
C++ function returning copy of the object from an array of objects. Is this the default behaviour?
我正在编写的程序变得非常复杂,因此我无法提供实际代码,但以下是确切的情况
有一个类,位置,位置有一个计数器(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);
相关文章:
- C++对象默认变量
- 在 C++ 中声明 const 对象需要用户定义的默认构造函数.如果我有一个可变成员变量,为什么不呢?
- 如何处理没有默认构造函数但在另一个构造函数中构造的对象?
- 在C++中使用默认构造函数初始化对象的不同方法
- 在没有默认构造函数的情况下创建的派生对象
- 使用默认构造函数初始化对象的不同方法
- 为什么指针对象没有调用默认构造函数
- 在没有默认构造函数时使用垃圾数据初始化对象
- 为什么对象默认初始化,但基元不在C++?
- 为什么在使用指针时不采用类成员的默认值,而不是直接实例化对象时?
- 为什么我的对象声明不调用默认构造函数?
- 如果普通默认构造函数不执行任何操作,为什么我们不能使用 malloc 创建平凡可构造的对象?
- 如何防止类中的类对象尝试在没有默认构造函数的情况下自动构造自身?
- 为什么用默认构造函数构造std::string对象时行为不同
- 声明成员对象而不调用其默认构造函数
- 可调用对象作为默认模板参数
- C++ 实例化新对象时不接受继承方法默认参数值
- 关于默认构造函数,对象初始化/使用C++ OOP
- C++ 创建不带默认构造函数的对象数组
- 在创建对象向量时,不为每个对象唯一调用默认对象构造函数