| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 589 人关注过本帖
标题:[求助]关于const引用的问题
只看楼主 加入收藏
wangweicoin
Rank: 1
等 级:新手上路
威 望:1
帖 子:58
专家分:0
注 册:2007-7-16
收藏
 问题点数:0 回复次数:7 
[求助]关于const引用的问题
最近看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;为什么呢?(是不是中间变量的问题)能不能具体解释一下。
还有可以绑定到右值是什么意思呢?
谢谢大家!!!
搜索更多相关主题的帖子: const 绑定 int 变量 
2007-09-17 08:30
wangweicoin
Rank: 1
等 级:新手上路
威 望:1
帖 子:58
专家分:0
注 册:2007-7-16
收藏
得分:0 
上边没说清楚,当然如果是这样就通过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;就不行呢?)。

~我的人生不是套公式~
2007-09-17 08:35
远去的列车
Rank: 1
等 级:新手上路
威 望:2
帖 子:205
专家分:0
注 册:2007-8-7
收藏
得分:0 
double i=41;
const int &r=i;

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

我也不明白

C++学习
2007-09-17 08:53
rediums
Rank: 2
等 级:新手上路
威 望:3
帖 子:367
专家分:0
注 册:2007-7-29
收藏
得分:0 
double i=41;
const int &r=i;

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

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

2007-09-17 09:22
HJin
Rank: 6Rank: 6
等 级:贵宾
威 望:27
帖 子:401
专家分:0
注 册:2007-6-9
收藏
得分:0 
回复:(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;
}


I am working on a system which has no Chinese input. Please don\'t blame me for typing English.
2007-09-17 10:06
hzdz
Rank: 2
等 级:论坛游民
帖 子:46
专家分:10
注 册:2007-2-3
收藏
得分:0 
其实书上后面也讲了,中间会有一个临时的 ( 假设是int temp=(int)i),所以真正r绑定的是这个temp,你改i,当然改不了
2007-09-17 12:41
wangweicoin
Rank: 1
等 级:新手上路
威 望:1
帖 子:58
专家分:0
注 册:2007-7-16
收藏
得分:0 
谢谢大家!!!懂了!Hjin大侠讲的很好。我也是看书不仔细啊!

~我的人生不是套公式~
2007-09-17 13:14
HJin
Rank: 6Rank: 6
等 级:贵宾
威 望:27
帖 子:401
专家分:0
注 册:2007-6-9
收藏
得分:0 
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.

I am working on a system which has no Chinese input. Please don\'t blame me for typing English.
2007-09-17 13:54
快速回复:[求助]关于const引用的问题
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.035709 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved