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

求高人指教,C++ const_cast有关问题

2013-01-23 
求高人指教,C++ const_cast问题OS:redHat5compile:g++先贴代码#include iostreamusing namespace stdin

求高人指教,C++ const_cast问题
OS:redHat5
compile:g++
先贴代码
#include <iostream>
using namespace std;
int main()
{
        const int a = 97;
        int &b = const_cast<int&>(a);
        b = 64;
        cout<<"b = "<<b<<endl;
        cout<<"a = "<<a<<endl;
        const string str("ttttttt");
        string &cstr = const_cast<string &>(str);
        cstr = "fffffff";
        cout<<"str = "<<str<<endl;
        cout<<"cstr = "<<cstr<<endl;
        return 0;
}
编译没有错误,运行结果:
b = 64
a = 97
str = fffffff
cstr = fffffff

问题:为什么string类型的const对象经过const_cast转换后,可以对const对象的值进行改变,而int型对象的值却没有发生变化



[解决办法]
You cannot use the const_cast operator to directly override a constant variable's constant status.
您不能使用const_cast会操作直接覆盖一个常量的恒定状态。

热点排行