引用作为函数参数?
我在引用方面遇到了麻烦。 考虑以下代码:
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);
//..
}
这里说 a
的值会增加 - 但为什么呢?
当调用true_increase(a)
时,将传递a
的副本。这将是一个不同的变量。因此&a
将与a
的真实地址不同。那么a
的值是如何增加的呢?
纠正我错误的地方。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
考虑以下示例:
这里的
b
可以被视为a
的别名。无论您分配给b
,也将分配给a
(因为b
是对a
的引用) 。通过引用
传递参数没有什么不同:Consider the following example:
Here
b
can be treated like an alias fora
. Whatever you assign tob
, will be assigned toa
as well (becauseb
is a reference toa
). Passing a parameterby reference
is no different:这就是你错的地方。将引用
a
。这就是参数类型旁边的&
的用途。发生在引用上的任何操作都会应用于引用对象。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.在 true_increase(int & a) 函数中,内部代码获取的不是您指定的整数值的副本。它是对整数值驻留在计算机内存中的同一内存位置的引用。因此,通过该引用完成的任何更改都将发生在您最初声明的实际整数上,而不是它的副本上。因此,当函数返回时,您通过引用对变量所做的任何更改都将反映在原始变量本身中。这就是C++中通过引用传递值的概念。
在第一种情况下,正如您所提到的,使用原始变量的副本,因此您在函数内所做的任何操作都不会反映在原始变量中。
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.