首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

const_cast转换后地址相同,内容不同,why?该怎么处理

2012-03-01 
const_cast转换后地址相同,内容不同,why?#include iostreamusingnamespacestdintmain(){constinta1in

const_cast转换后地址相同,内容不同,why?
#include <iostream>
using   namespace   std;
int   main()
{
        const   int   a=1;
        int   &b=const_cast <int&> (a);
        cout < <a < <endl;
        b=2;
        cout < <&b < < ": " < <*(&b) < <endl;
        cout < <&a < < ": " < <*(&a) < <endl;
        cout < <typeid(&a).name() < <endl;
        cout < <typeid(&b).name() < <endl;
system( "pause ");
return   0;
}

output:
1
0x22ff74:2
0x22ff74:1
PKi               //这个这么解释?
Pi               //这个这么解释?
为什么相同的地址可以取不同的值,一个地址可以存放两个不同的值么?const_cast到底做了什么?
PKi,Pi   是什么类型!
const_cast在进行常量转换的时候他可以取得const对象的地址,生成一个指向const的指针-- <thinking   in   c++>
请大家帮忙看看,thank   you!




[解决办法]
thinking in C++在cosnt那一章,不真是专门讲了这个常量折叠问题嘛。
你把int换成double再试试。
[解决办法]
编译器先把“*(&a)”优化成了a,然后看到a是个const int,又接着给优化成了5。
但这种游戏不一定每种编译器都灵的,因为通过编程技巧偷偷修改一个const量,其后果是未定义的。
[解决办法]
VC6下运行:

1
0012FF80:2
0012FF80:1
int const *
int *
请按任意键继续. . .
[解决办法]
steedhorse(晨星)

正解

热点排行