考虑以下:
int someA = 1;
int someB = 2;
int &a = someA;
int &b = someB;
a = b; // what happens here?
引用这里发生了什么?只是好奇。
考虑以下:
int someA = 1;
int someB = 2;
int &a = someA;
int &b = someB;
a = b; // what happens here?
引用这里发生了什么?只是好奇。
拥有两个彼此相等的参考变量本身并不是错误。这可能会令人困惑。但是,您的代码所做的不是设置对另一个引用的引用,而是更改_A
from1
到的值2
,这就是_B
.
您只能设置一次引用 [在哪里初始化]。一旦它被初始化,它将成为原始变量的别名。
你可以这样做:
int &a = _A;
int &b = _A;
和
a = b;
会将值存储1
到_A
已经具有值的1
中。
你不能在函数之外有语句。
a = b; //compile error?
这是一个语句,所以必须在一个函数中:
int _A = 1;
int _B = 2;
int &a = _A;
int &b = _B;
int main()
{
a = b; //compile error? No. Now it compiles.
// As 'a' and 'b' are references.
// This means they are just another name for an already existing variable
// ie they are alias
//
// It means that it is equivalent to using the original values.
//
// Thus it is equivalent too:
_A = _B;
}
现在它编译了。
这里没有错误,但我想我可能知道你对什么感到困惑。不会重新分配引用,但是会重新分配它所引用的值。
因此,当您这样做时,a = b;
您实际上是在说:_A = _B
,因为引用是别名。
永远不能像指针一样重新分配引用。
引用也永远不能为空。