References as function arguments?

隐身守侯 提交于 2019-12-10 13:26:45

问题


I have a trouble with references. Consider this code:

void pseudo_increase(int a){a++;}  
int main(){  
    int a = 0;
    //..
    pseudo_increase(a);
    //..
}

Here, the value of variable a will not increase as a clone or copy of it is passed and not variable itself.
Now let us consider an another example:

void true_increase(int& a){a++;}
int main(){  
    int a = 0;
    //..
    true_increase(a);
    //..
}

Here it is said value of a will increase - but why?

When true_increase(a) is called, a copy of a will be passed. It will be a different variable. Hence &a will be different from true address of a. So how is the value of a increased?

Correct me where I am wrong.


回答1:


Consider the following example:

int a = 1;
int &b = a;
b = 2; // this will set a to 2
printf("a = %d\n", a); //output: a = 2

Here b can be treated like an alias for a. Whatever you assign to b, will be assigned to a as well (because b is a reference to a). Passing a parameter by reference is no different:

void foo(int &b)
{
   b = 2;
}

int main()
{
    int a = 1;
    foo(a);
    printf("a = %d\n", a); //output: a = 2
    return 0;
}



回答2:


When true_increase(a) is called , copy of 'a' will be passed

That's where you're wrong. A reference to a will be made. That's what the & is for next to the parameter type. Any operation that happens to a reference is applied to the referent.




回答3:


in your true_increase(int & a) function, what the code inside is getting is NOT A COPY of the integer value that you have specified. it is a reference to the very same memory location in which your integer value is residing in computer memory. Therefore, any changes done through that reference will happen to the actual integer you originally declared, not to a copy of it. Hence, when the function returns, any change that you did to the variable via the reference will be reflected in the original variable itself. This is the concept of passing values by reference in C++.

In the first case, as you have mentioned, a copy of the original variable is used and therefore whatever you did inside the function is not reflected in the original variable.



来源:https://stackoverflow.com/questions/8921554/references-as-function-arguments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!