找回密码
 注册
搜索
热搜: 回贴
  • 前程无忧官网首页 有什么好的平台可以
  • 最新的销售平台 互联网营销的平台有哪
  • 制作网页的基本流程 网页制作和网页设
  • 【帝国CMS】输出带序号的列表(数字排
  • 网站建设公司 三一,中联,极东泵车的
  • 织梦 建站 织梦网站模版后台怎么更改
  • 云服务官网 哪些网站有免费的简历模板
  • 如何建网站要什么条件 建网站要用什么
  • 吉林市移动公司电话 吉林省退休人员网
  • 设计类毕业论文 网站设计与实现毕业论
查看: 1006|回复: 7

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

[复制链接]
发表于 2009-11-3 01:03:00 | 显示全部楼层 |阅读模式 IP:江苏扬州
最近看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;为什么呢?(是不是中间变量的问题)能不能具体解释一下。
还有可以绑定到右值是什么意思呢?
谢谢大家!!!
发表于 2009-11-3 01:03:01 | 显示全部楼层 IP:江苏扬州
上边没说清楚,当然如果是这样就通过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;就不行呢?)。
回复

使用道具 举报

发表于 2009-11-3 01:03:05 | 显示全部楼层 IP:江苏扬州
double i=41;
const int &r=i;

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

我也不明白
回复

使用道具 举报

发表于 2009-11-3 01:03:07 | 显示全部楼层 IP:江苏扬州
double i=41;
const int &r=i;

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

注:标准c++规定,临时对象可以用作const引用或命名对象的初始式
回复

使用道具 举报

发表于 2009-11-3 01:03:08 | 显示全部楼层 IP:江苏扬州
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;
}
回复

使用道具 举报

发表于 2009-11-3 01:03:10 | 显示全部楼层 IP:江苏扬州
其实书上后面也讲了,中间会有一个临时的 ( 假设是int temp=(int)i),所以真正r绑定的是这个temp,你改i,当然改不了
回复

使用道具 举报

发表于 2009-11-3 01:03:13 | 显示全部楼层 IP:江苏扬州
谢谢大家!!!懂了!Hjin大侠讲的很好。我也是看书不仔细啊!
回复

使用道具 举报

发表于 2009-11-3 01:03:16 | 显示全部楼层 IP:江苏扬州
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.
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

QQ|小黑屋|最新主题|手机版|微赢网络技术论坛 ( 苏ICP备08020429号 )

GMT+8, 2024-9-30 05:27 , Processed in 0.224439 second(s), 12 queries , Gzip On, MemCache On.

Powered by Discuz! X3.5

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表