[英]Sub-functions with reference parameter : how it works?
I originally show the a program, which have a sub-function with non reference parameter like below: 我最初显示一个程序,它有一个非参考参数的子函数,如下所示:
#include<iostream>
using namespace std;
int inc(int x)
{
x++;
return x;
}
main()
{
n=3;
inc(n);
cout<<n;
}
I think that about sub-function and may be it works like below: 我认为关于子功能,可能会像下面这样工作:
when we call inc(n)
, after that may be computer will create a var int m;
当我们调用inc(n)
,之后可能会在计算机上创建一个var int m;
and: 和:
m=n; m++;
and finally it is erased. 最后它被删除了。
With sub-function with reference parameter : 带参数参数的子功能:
#include<iostream>
using namespace std;
int inc(int &x)
{
x++;
return x;
}
main()
{
n=3;
inc(n);
cout<<n;
}
I think: 我认为:
when we call inc(n)
, after that may be computer will create a var int &m=n
; 当我们调用inc(n)
,之后可能是计算机会创建一个var int &m=n
; m++; return m;
and finally it is erased, but n
is changed by n+1
. 最后它被删除,但是n
被n+1
改变了。
Why am I asking? 我为什么要问? There are 2 reasons: 1) My fiend say that : there is not creation int &m
, function inc(int &x)
works such as : n run into and go out. 有两个原因:1)我的恶魔说:没有创建int &m
, function inc(int &x)
工作原理如下:n进入和退出。 2) If there is int &m
why everyone always say " inc (int &x)
faster inc(int x)
"? 2)如果有int &m
为什么每个人总是说“ inc (int &x)
fast inc(int x)
”?
Is my understanding of this correct? 我对此的理解是否正确? If not, can you tell me why? 如果没有,你能告诉我为什么吗?
From the compiler point of view, a reference is not far from a pointer. 从编译器的角度来看,引用距指针不远。 So in 所以
int inc(int &x)
{
x++;
return x;
}
...
inc(n);
you only pass a reference (the address of the variable n
) to the function, and the callee variable is actually increased. 您只将引用(变量n
的地址)传递给函数,并且实际上增加了被调用者变量。
Whereas in 而在
int inc(int x)
{
x++;
return x;
}
...
inc(n);
you pass by value and you are modifying a local copy. 您传递值并且您正在修改本地副本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.