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

LGuitars 2013-01-02 11:51:34
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型对象的值却没有发生变化

...全文
174 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
LGuitars 2013-01-03
  • 打赏
  • 举报
回复
怎么没人啊,都过元旦去了?
LGuitars 2013-01-03
  • 打赏
  • 举报
回复
明白了,多谢2楼!
jimette 2013-01-03
  • 打赏
  • 举报
回复
You cannot use the const_cast operator to directly override a constant variable's constant status. 您不能使用const_cast会操作直接覆盖一个常量的恒定状态。

64,646

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧