引用作为函数参数? [英] References as function arguments?
问题描述
我有参考的麻烦。
考虑这个代码:
void pseudo_increase(int a){a ++;}
int main {
int a = 0;
// ..
pseudo_increase(a);
// ..
}
这里,变量 a
void true_increase(int& a){a ++;}
int main(){
int a = 0;
// ..
true_increase(a);
// ..
}
这里说的是<$ true_increase(a)$ <$>
a
的副本。它将是一个不同的变量。因此,& a
将与 a
的真实地址不同。那么 a 的价值是如何增加的?
请考虑以下示例:
<$ c $ <$>
int& b = a;
b = 2; // this will set a to 2
printf(a =%d\\\
,a); // output:a = 2
这里 b
对于 a
可以像别名一样处理。无论您分配给 b
,也会分配给 a
(因为 b
是对
a
的引用)。通过引用传递参数没有什么不同:
void foo & b)
{
b = 2;
}
int main()
{
int a = 1;
foo(a);
printf(a =%d\\\
,a); // output:a = 2
return 0;
}
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.
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;
}
这篇关于引用作为函数参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!