注册 登录
编程论坛 C++教室

[求助]关于const引用的问题

wangweicoin 发布于 2007-09-17 08:30, 595 次点击
最近看C++ primer,书上说const引用可以绑定到不同单相关的类型对象或绑定到右值。我自己试了一下:
#include<iostream>
using namespace std;
int main()
{
double i=41;
const int &r=i;
i=5;
cout<<i<<" "<<r<<endl;
return 0;
}
发现改变i的值以后r的值并没有发生改变,就是输出5和41;为什么呢?(是不是中间变量的问题)能不能具体解释一下。
还有可以绑定到右值是什么意思呢?
谢谢大家!!!
7 回复
#2
wangweicoin2007-09-17 08:35
上边没说清楚,当然如果是这样就通过i可以改变r的值。
#include<iostream>
using namespace std;
int main()
{
int i=41;
const int &r=i;
i=5;
cout<<i<<" "<<r<<endl;
return 0;
}
这是我的疑惑(为什么double i=41;const int& r=i;就不行呢?)。
#3
远去的列车2007-09-17 08:53
double i=41;
const int &r=i;

i 由 double 型转换成 int 型,会不会由一个空间存起来,然后 r 是对这个空间( (int)i )的引用而不是 i 的引用???

我也不明白
#4
rediums2007-09-17 09:22
double i=41;
const int &r=i;

i的值首先由double类型转化为一个int类型,此时,系统用一个临时的int类型的变量存储这个转化后的值,
所以,const int &r 得到的是这个临时变量的值

注:标准c++规定,临时对象可以用作const引用或命名对象的初始式
#5
HJin2007-09-17 10:06
回复:(wangweicoin)[求助]关于const引用的问题

You can debug your program --- which may tell you why.
=======================================================

#include<iostream>
using namespace std;
int main()
{
/** test 1

In this test, &i != &r; i.e., memory
locations of the two variables are
different.

I don't know why this is happening.
*/
double i=45;
const int &r=i;
cout<<&i<<" "<<&r<<endl;
i=5;
i=6;
cout<<i<<" "<<r<<endl;

/** test 2

In this test, both i2 and r2 share the same
memory location.
*/
int i2=41;
const int &r2=i2;
cout<<&i2<<" "<<&r2<<endl;

i2=5;
i2=6;
cout<<i2<<" "<<r2<<endl;

return 0;
}

#6
hzdz2007-09-17 12:41
其实书上后面也讲了,中间会有一个临时的 ( 假设是int temp=(int)i),所以真正r绑定的是这个temp,你改i,当然改不了
#7
wangweicoin2007-09-17 13:14
谢谢大家!!!懂了!Hjin大侠讲的很好。我也是看书不仔细啊!
#8
HJin2007-09-17 13:54
thanks for your compliment. I don't really answer your question --- I think other friends have answered your question.

It is because there is a temporaray vairable there.
1