&在函数声明返回类型
问题描述:
什么是&在下面是什么意思?
What does the & mean in the following?
class Something
{
public:
int m_nValue;
const int& GetValue() const { return m_nValue; }
int& GetValue() { return m_nValue; }
};
此代码取自这里。
答
int& GetValue()
^ Means returns a reference of int
像
int i = 10;
int& GetValue() {
int &j = i;
return j;
}
注意:在C ++中有三种变量:
Note: In C++ you have three kinds of variables:
- 值变量例如
int i = 10
。 - 引用变量例如
int& j = i;
引用变量创建其他变量的别名,都是同一内存位置的符号名称。 - 地址变量:
int * ptr =& i
。称为指针。指针变量用于保存变量的地址。
- Value variable for example
int i = 10
. - Reference variable for example
int &j = i;
reference variable creates alias of other variable, both are symbolic names of same memory location. - Address variable:
int* ptr = &i
. called pointers. Pointer variables use for holding address of a variable.
声明中的参数
Pointer:
int *ptr = &i;
^ ^ & is on the left side as an address operation
|
* For pointer variable.
Reference:
int &j = i;
^
| & on the right side for reference
记住在C你只有两种变量值和地址)。引用变量在C ++中,引用很容易使用,如值变量和指针变量一样。
Remember in C you have only two kinds of variables value and address (pointer). Reference variables are in C++, and references are simple to use like value variables and as capable as pointer variables.
指针如下:
j = &i;
i j
+------+ +------+
| 10 | | 200 |
+------+ +------+
202 432
参考如下:
int &j = i;
i, j
+------+
| 10 |
+------+
没有给j分配内存。它是内存中相同位置的别名。
No memory is allocated for j. It's an alias of the same location in memory.
What are the differences between pointer variable and reference variable in C++?
- 指针可以重新分配任何次数,而引用初始化后无法重新分配。
- 指针可以指向NULL,而引用永远不能指向NULL
- 不能像指针一样获取引用的地址
- 没有引用算术(但你可以取一个引用指向的对象的地址,并在其上做指针算术,如& obj + 5)。
- A pointer can be re-assigned any number of times while a reference can not be reassigned after initialization.
- A pointer can point to NULL while a reference can never point to NULL
- You can’t take the address of a reference like you can with pointers
- There’s no "reference arithmetics" (but you can take the address of an object pointed by a reference and do pointer arithmetics on it as in &obj + 5).
因为你评论过,你对指针和引用变量之间的差异有疑问,所以我强烈建议你从我给出的链接中读取相关页面我的回答。