在函数中通过引用传递的对象

Object pass by reference in a fuction

本文关键字:对象 引用 函数      更新时间:2023-10-16

所以我试图在一个函数中改变另一个函数中的对象值,但值保持不变。不好意思,我还是个新手。

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;
}