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

时间:2015-06-05 11:44:43

标签: c++

所以我试图用另一个函数改变一个函数中的对象值,但值保持不变。抱歉编码不好,我还是个菜鸟。

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.

1 个答案:

答案 0 :(得分:0)

替换您的对象并使用此格式通过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;
}