-1

考虑以下:

int someA = 1;
int someB = 2;

int &a = someA;
int &b = someB;

a = b;   // what happens here?

引用这里发生了什么?只是好奇。

4

3 回答 3

6

拥有两个彼此相等的参考变量本身并不是错误。这可能会令人困惑。但是,您的代码所做的不是设置对另一个引用的引用,而是更改_Afrom1到的值2,这就是_B.

您只能设置一次引用 [在哪里初始化]。一旦它被初始化,它将成为原始变量的别名。

你可以这样做:

int &a = _A;
int &b = _A;

a = b;  

会将值存储1_A已经具有值的1中。

于 2013-02-06T14:06:46.860 回答
3

你不能在函数之外有语句。

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;
}

现在它编译了。

于 2013-02-06T14:07:43.550 回答
2

这里没有错误,但我想我可能知道你对什么感到困惑。不会重新分配引用,但是会重新分配它所引用的值。

因此,当您这样做时,a = b;您实际上是在说:_A = _B,因为引用是别名。

永远不能像指针一样重新分配引用。

引用也永远不能为空。

于 2013-02-06T14:06:54.060 回答