读书人

int yyy = const_castlt;intamp;gt; (xxx); 为

发布时间: 2013-12-22 15:06:55 作者: rapoo

int yyy = const_cast<int&> (xxx); 为什么得到another int
const int xxx = 50;
int yyy = const_cast<int&> (xxx);// another int //得到another int (为什么?)
yyy = 200;
cout << "xxx:"<<xxx<<" address: "<<&xxx<<endl; //result: xxx: 50 address: 002CF88C
cout << "yyy:"<<yyy<<" address: "<<&yyy<<endl; //result: yyy: 200 address: 002CF888
[解决办法]
不管你怎么转换
int yyy = const_cast<int&> (xxx);
这左边都是int而不是int &
所以是不可能引用的,只会弄个新副本
[解决办法]

引用:
Quote: 引用:

不管你怎么转换
int yyy = const_cast<int&> (xxx);
这左边都是int而不是int &
所以是不可能引用的,只会弄个新副本

&我不懂,int&什么意思?

int yyy就是定义一个新的变量,所以地址肯定是不同的。
int&则是引用,对变量xxx取了一个别名,两者是同一个变量,所以地址会相同。

至于xxx和yyy值不同,则是C++的常量折叠问题,即使用了引用值还是不同的。

读书人网 >C++

热点推荐