0

使用 GCC 4.8.1 (MinGW) 编译命令:g++ -o test.exe test.cpp

测试.cpp

#include <iostream>

int a = 1, b = 2;

void F()
{
    int &r = a;
    std::cout << r;
    r = b;
    std::cout << r;
}

int main ( int, char** )
{
    F();
    F();
    return 0;
}

预期输出为:1212,但实际输出为:1222

r当被定义为指针时,它按预期工作。

void F()
{
    int *r = &a;
    std::cout << *r;
    r = &b;
    std::cout << *r;
}

有人知道“帐篷的钥匙”在哪里吗?

4

4 回答 4

3

在带有指针的示例中:

r = &b;

这将重新定位指向 的r指针b。在带有参考的示例中:

r = b;

您可能认为这类似于带有指针的示例,但事实并非如此。引用不能像指针那样重新定位。一旦它们被初始化,它们就会成为它们引用的事物的别名。所以上面的行完全等价于:

a = b;

也就是说,它将存储在bover 中的值复制到a.

参考示例可以这样写:

void F()
{
    std::cout << a;
    a = b;
    std::cout << a;
}

虽然指针示例可以这样写:

void F()
{
    std::cout << a;    
    std::cout << b;
}
于 2013-10-21T09:17:33.863 回答
1

您的“问题”是以下行:

int &r = a;

这将创建一个所谓的指向a. 虽然引用在访问它们时不需要额外的逻辑(即取消引用;与指针相比),但它们在幕后仍然以相同的方式工作。

所以一旦你上线

r = b;

您将实际使用引用并更新a. 在这种情况下r,它永远不会有它自己的价值。它总是指向a并且本质上是一个别名。

在您的第二个示例中,这是不同的。线

int *r = &a;

创建一个指向aand的指针

r = &b;

将重新分配该地址,使指针现在指向b.

简而言之,当您为指针分配一些其他值(地址)时,您更改了指针,它将指向其他地方。但是,当为引用分配新值时,您实际上是在更新它所引用的初始而不是引用本身

于 2013-10-21T09:19:16.620 回答
0
//global variables! remember that this will be like a state
//and will be freed on (data?BSS?stack?) only after end of program.
int a = 1, b = 2;

void F()
{
    //You are referencing here,
    //meaning, once you change the referee ( r )
    //the reference will changed permanently.
    //Permanently because you are referring to a global variable.
    int &r = a;        

    std::cout << r;

    //You have changed the value of ( r )
    //forever!

    r = b;   //I think you are assuming the you have changed the reference address here?
    std::cout << r;
}

void F()
{
    //You have declared and initialized a pointer
    //that points to global variable.
    //w/c means you can also change its value forever!
    int *r = &a;
    std::cout << *r;

    //You have changed the ( r ) address pointing to, not its value!
    r = &b;
    std::cout << *r;
}
于 2013-10-21T09:38:30.050 回答
0
Your code is absolutely fine and it's working according to your instruction.
Suppose a variable has 1000 address b variable 1004 address, now your first line is  
         int &r = a;
that means r has 1000 address  and you did cout<< r //print 1
In second statement  r = b that means 1000 address hold value of b means 2;
Now , your scenario has been changed 1000---> 2 and 1004--->2 

and again you are calling F();
that's why compiler print twice 2 value. . There is a concept referencing in c++. Hope it  
would be useful for u
于 2013-10-21T09:49:48.750 回答