在函数中通过引用传递的对象
Object pass by reference in a fuction
所以我试图在一个函数中改变另一个函数中的对象值,但值保持不变。不好意思,我还是个新手。
void fun2(sampleObject &test){
sampleObject &temp = test;
//I called the setter to change the value of the first int.
temp.setFirst(temp.getFirst() - 2);
//Doesn't work with test.setFirst(test.getFirst() - 2);
}
void fun1(){
/*sampleObject is a class that was created.
with a constructor of (int, int, string);
*/
sampleObject test[1];
test[0] = {100, 30, "Hello"};
//fun2 should change the first int value.
fun2(test[0]);
cout << "First number in test 0 is " << test[0].getFirst();
//Prints 100 instead of 98.
}
int main(){
fun1();
return 0;
}
//No luck.
用ref
替换你的对象并使用这个格式来改变数组的值void func2(int &test){
int &temp = test;
temp = temp-2;
}
void func1(){
int test[1];
test[0] = 100;
func2(test[0]);
cout << test[0];
}
int main() {
func1(); //Print 98
return 0;
}
相关文章:
- 返回常量对象引用 (getter) 和仅返回字符串有什么区别?
- 我们可以有一个 setter 成员函数作为从 const 对象引用的 const 吗?
- C++对象引用返回不同的值
- 对象引用中的字段以不同的方法返回不同的值
- 通过向构造函数其他对象引用页面来创建对象
- 为什么在对象引用恒定时允许更改为另一个类的指针的成员变量
- 如何在C++中读取 HDF5 对象引用
- C++ 未定义的对象引用
- 从函数返回 libconfig 类设置对象引用
- qt vsaddin错误对象引用未设置为对象的istanse
- 在这种情况下,为什么使用 *此必需的对象引用返回对象引用
- 基本C - 构造contaning对象引用,并将其作为方法参数传递
- C :将对象引用作为参数给出错误:呼叫class :: function()的匹配函数
- C++OOP基础知识-是否正确返回对象引用
- 使用对象引用(可能)在调用destructor后使用对象引用
- 创建返回对象引用的成员函数的最简单方法
- 如何在C++上使用对象引用删除对象
- JNI/Android NDK-维护全局对象引用
- 为什么有些类方法返回"*this"(self的对象引用)?
- 在C++中返回伪对象引用的规则