什么是int&意思 [英] What does int & mean
问题描述
一个C ++问题,
我知道
int * foo(void)
foo将返回指向int类型的指针
如何
int& foo(void)
它是什么?
非常感谢!
解决方案它返回一个引用到一个int。引用类似于指针,但有一些重要的区别。我建议您阅读指针,引用,对象和原始数据类型之间的差异。
有效的C ++和更有效的C ++ Meyers)有一些很好的描述差异和何时使用指针vs引用。
编辑:有很多答案说,语法糖以更容易处理指针。
请考虑以下代码:
int a = 3;
int b = 4;
int * pointerToA =& a;
int * pointerToB =& b;
int * p = pointerToA;
p = pointerToB;
printf(%d%d%d \\\
,a,b,* p); // Prints 3 4 4
int& referenceToA = a;
int& referenceToB = b;
int& r = referenceToA;
r = referenceToB;
printf(%d%d%d \\\
,a,b,r); // Prints 4 4 4
行
p = pointerToB
更改p
的值,即它现在指向不同的内存块。
r = referenceToB
完全不同:它分配b
到
a
的值。它不更改r
。r
仍然是对同一块内存的引用。
区别是微妙但非常重要。 p>
如果你仍然认为引用只是用于指针处理的语法糖,请阅读Scott Meyers的书。他可以比我更好地解释差异。
A C++ question,
I know
int* foo(void)
foo will return a pointer to int type
how about
int &foo(void)
what does it return?
Thank a lot!
解决方案It returns a reference to an int. References are similar to pointers but with some important distinctions. I'd recommend you read up on the differences between pointers, references, objects and primitive data types.
"Effective C++" and "More Effective C++" (both by Scott Meyers) have some good descriptions of the differences and when to use pointers vs references.
EDIT: There are a number of answers saying things along the lines of "references are just syntactic sugar for easier handling of pointers". They most certainly are not.
Consider the following code:
int a = 3; int b = 4; int* pointerToA = &a; int* pointerToB = &b; int* p = pointerToA; p = pointerToB; printf("%d %d %d\n", a, b, *p); // Prints 3 4 4 int& referenceToA = a; int& referenceToB = b; int& r = referenceToA; r = referenceToB; printf("%d %d %d\n", a, b, r); // Prints 4 4 4
The line
p = pointerToB
changes the value ofp
, i.e. it now points to a different piece of memory.
r = referenceToB
does something completely different: it assigns the value ofb
to where the value ofa
used to be. It does not changer
at all.r
is still a reference to the same piece of memory.The difference is subtle but very important.
If you still think that references are just syntactic sugar for pointer handling then please read Scott Meyers' books. He can explain the difference much better than I can.
这篇关于什么是int&意思的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!