下面的 & 是什么意思?
class Something
{
public:
int m_nValue;
const int& GetValue() const { return m_nValue; }
int& GetValue() { return m_nValue; }
};
此代码取自此处。
下面的 & 是什么意思?
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;
}
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 分配内存。它是内存中同一位置的别名。
因为正如您评论的那样,您对指针和引用变量之间的差异有疑问,所以我强烈建议您从我在回答中给出的链接中阅读相关页面。