C++ 变量类型后的“&”含义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11604190/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
"&" meaning after variable type
提问by vico
Possible Duplicate:
What are the differences between pointer variable and reference variable in C++?
What's the meaning of * and & when applied to variable names?
Trying to understand meaning of "&
" in this situation
&
在这种情况下试图理解“ ”的含义
void af(int& g)
{
g++;
cout<<g;
}
If you call this function and pass variable name - it will act the same like normal void(int g)
. I know, when you write &g
that means you are passing address of variable g
. But what does it means in this sample?
如果你调用这个函数并传递变量名 - 它会像正常一样工作void(int g)
。我知道,当你写&g
这意味着你正在传递变量的地址g
。但它在这个样本中意味着什么?
回答by Luchian Grigore
It means you're passing the variable by reference.
这意味着您正在通过引用传递变量。
In fact, in a declaration of a type, it means reference, just like:
事实上,在一个类型的声明中,它的意思是引用,就像:
int x = 42;
int& y = x;
declares a reference to x
, called y
.
声明对 的引用x
,称为y
。
回答by cegfault
The &
means that the function accepts the address(or reference) to a variable, instead of the valueof the variable.
这&
意味着函数接受变量的地址(或引用),而不是变量的值。
For example, note the difference between this:
例如,注意这两者之间的区别:
void af(int& g)
{
g++;
cout<<g;
}
int main()
{
int g = 123;
cout << g;
af(g);
cout << g;
return 0;
}
And this (without the &
):
而这个(没有&
):
void af(int g)
{
g++;
cout<<g;
}
int main()
{
int g = 123;
cout << g;
af(g);
cout << g;
return 0;
}