使用命令:g++ -o test.exe test.cpp
TEST.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;
}
有人知道“帐篷里的钥匙”在哪里吗?
答案 0 :(得分:3)
在带指针的示例中:
r = &b;
这会将指针r
重新置于指向b
的位置。在带引用的示例中:
r = b;
您可能认为这与指针的示例类似,但事实并非如此。引用不像指针那样可以重新定位。一旦它们被初始化,它们就成为它们引用的东西的别名。所以上面的行与此完全相同:
a = b;
也就是说,它会将b
中存储的值复制到a
。
参考示例可以这样写:
void F()
{
std::cout << a;
a = b;
std::cout << a;
}
虽然指针示例可以这样写:
void F()
{
std::cout << a;
std::cout << b;
}
答案 1 :(得分:1)
您的“问题”如下:
int &r = a;
这将创建一个指向a
的所谓引用。虽然引用在访问它们时不需要额外的逻辑(即解除引用;与指针相比),但它们仍然在幕后工作方式相同。
所以一旦你点击
r = b;
您实际上将使用该引用并更新a
的值。在这种情况下,r
永远不会拥有它自己的价值。它始终指向a
并且基本上是别名。
在你的第二个例子中,这是不同的。这条线
int *r = &a;
创建一个指向a
和
r = &b;
将重新分配该地址,使指针现在指向b
。
简而言之,当您将一些其他值(地址)指定给指针时,您更改指针,它将指向其他位置。但是,在为参考分配新值时,实际上是在更新值,其中引用,而非参考本身。
答案 2 :(得分: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;
}
答案 3 :(得分: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