读书人

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

发布时间: 2013-01-23 10:44:49 作者: rapoo

求高人指教,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会操作直接覆盖一个常量的恒定状态。

读书人网 >C++

热点推荐