&以下是什么意思?
class Something
{
public:
int m_nValue;
const int& GetValue() const { return m_nValue; }
int& GetValue() { return m_nValue; }
};
此代码取自here。
答案 0 :(得分:5)
It means return value by reference:
int& GetValue()
^ Means returns a reference of int
像
int i = 10;
int& GetValue() {
int &j = i;
return j;
}
j
是i
的引用,是一个全局变量。
注意:在C ++中,您有三种变量:
int i = 10
。int &j = i;
引用变量创建其他变量的别名,两者都是相同内存位置的符号名称。int* ptr = &i
。叫做指针。指针变量用于保存变量的地址。声明中的尊重
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 ++中,引用很容易使用,如值变量和指针变量。
指针就像:
j = &i;
i j
+------+ +------+
| 10 | | 200 |
+------+ +------+
202 432
参考文献如下:
int &j = i;
i, j
+------+
| 10 |
+------+
没有为j分配内存。它是内存中相同位置的别名。
What are the differences between pointer variable and reference variable in C++?
因为你评论过,你对指针和引用变量之间的差异有疑问,所以我强烈建议你从我在答案中给出的链接中阅读相关页面。