const_cast示例
来源:互联网 发布:阿里云短信 regionid 编辑:程序博客网 时间:2024/05/20 07:36
const_cast用于对"const"或"volatile"进行转换。
代码1
int main(){ const int i = 0; int *j; j = const_cast<int*>(&i); cout << &i << " "<< j << endl; cout << i << " " << *j << endl;
*j = 1; cout << &i << " "<< j << endl; cout << i << " " << *j << endl; return 0;}结果1
0xbf9dec84 0xbf9dec840 00xbf9dec84 0xbf9dec840 1
本来想通过const_cast得到的指针,修改i的内容,但结果并没有成功。i的值还是0,跟同学讨论,估计是编译对const值进行了优化,直接在程序中替换了。
代码2
int main(){ const int i = 0; const int &ii = const_cast<int &>(i); int *j; j = const_cast<int*>(&ii); cout << &ii << " "<< j << endl; cout << ii << " " << *j << endl;
*j = 1;
cout << &ii << " "<< j << endl; cout << ii << " " << *j << endl; cout << i << endl; return 0;}结果2
0xbf5d9084 0xbf5d90840 00xbf5d9084 0xbf5d90841 10i的值还是没有改变。
代码3
class A { public: int val; public: A(int v) : val(v) { };};intmain() { const A a(1); A* p = const_cast<A *>(&a); p->val = 2; cout << &a << " " << p << endl; cout << a.val << endl; cout << p->val << endl;}
结果3
0xbf5fd8a8 0xbf5fd8a822
对象a的val值被改变了,是因为类对象没有被优化么??
- const_cast示例
- const_cast
- const_cast
- const_cast
- const_cast
- const_cast
- const_cast
- const_cast
- const_cast
- const_cast
- const_cast
- const_cast
- const_cast
- const_cast
- const_cast
- const_cast
- const_cast
- const_cast.cpp
- 刘勇 - 购物狂欢节的运维故事
- Makefile内置变量,递归式变量,直接展开式变量,条件赋值,追加赋值,Makefile中shell命令的执行
- 世界十大最漂亮钞票
- Android UI开发第十九篇——介绍一个开源的gifview——Android显示GIF动画
- JVM参数
- const_cast示例
- java中io流下载文件实例
- 使用ld的wrap选项替换已有库函数
- CentOS 安装中文输入法
- JavaScript实现页面跳转的几种方式
- memory hotplug
- Opencv中的cvWaitkey函数的用法
- Java JList应用
- Android UI开发第二十篇——仿launcher的左右滑动(用ViewPager实现欢迎引导页面)