const_cast的应用
来源:互联网 发布:vb.net数据库放到内存 编辑:程序博客网 时间:2024/05/16 09:58
对于const变量,我们不能修改它的值,这是这个限定符最直接的表现。但是我们就是想违背它的限定希望修改其内容怎么办呢?于是我们可以使用const_cast转换符是用来移除变量的const限定符。
const_cast类型转换能够剥离一个对象的const属性,也就是说允许你对常量进行修改。
const_cast类型转换能够剥离一个对象的const属性,也就是说允许你对常量进行修改。
#include<iostream>using namespace std;/*用法:const_cast<type_id> (expression) 该运算符用来修改类型的const或volatile属性。除了const 或volatile修饰之外, type_id和expression的类型是一样的。 一、常量指针被转化成非常量指针,并且仍然指向原来的对象; 二、常量引用被转换成非常量引用,并且仍然指向原来的对象; 三、常量对象被转换成非常量对象。 type_id 必须为指针或引用*/class B{public:int m_iNum;B() : m_iNum(50){ }};void foo(){const B *b1 = new B();//b1->m_iNum = 100; // 编译错误// 做如下转换,体现出转换为指针类型B *b2 = const_cast<B*>(b1);b2->m_iNum = 200;cout<<"b1: "<< b1->m_iNum <<endl;cout<<"b2: "<< b2->m_iNum <<endl;const B b3;//b3.m_iNum = 100; // 编译错误B b4 = const_cast<B&>(b3); // b4是另外一个对象b4.m_iNum = 200;cout<<"b3: "<<b3.m_iNum <<endl;cout<<"b4: "<<b4.m_iNum <<endl;const B b5;//b5.m_iNum = 100; // 编译错误// 或者左侧也可以用引用类型,如果对b6的数据成员做改变,就是对b5的值在做改变B &b6 = const_cast<B&>(b5);b6.m_iNum = 200;cout<<"b5: "<<b5.m_iNum <<endl;cout<<"b6: "<<b6.m_iNum <<endl;// force to convert const int x = 50;int* y = (int *)(&x); // 同样的地址,但是内容是不一样的*y = 200;cout << "x: "<<x<<" address: "<<&x<<endl;cout << "*y: "<<*y<<" address: "<<y<<endl;cout<<endl;const int xx = 50;int* yy = const_cast<int *> (&xx); // 同样的地址,但是内容是不一样的*yy = 200;cout << "xx: "<<xx<<" address: "<<&xx<<endl;cout << "*yy: "<<*yy<<" address: "<<yy<<endl;cout<<endl;// intconst int xxx = 50;int yyy = const_cast<int&> (xxx); // yyy是另外一个int对象yyy = 200;cout << "xxx: "<<xxx<<" address: "<<&xxx<<endl;cout << "yyy: "<<yyy<<" address: "<<&yyy<<endl;}int main(void){foo();return 0;}运行结果如下:
- const_cast的应用
- const_cast的应用
- const_cast的应用
- const_cast的应用
- const_cast应用
- 【Oracle在线笔试题】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的用法
- N列等高
- android Handler 介绍(一)
- 博客搬家
- oracle函数大全 oracle所有函数举例说明
- Ogre中Fresnel例子分析
- const_cast的应用
- USB接口IC读写器oem软件_AB密码完整解决方案/读写卡测试程序及源代码/c++builder源代码(2)
- 自定义Alert样式
- android 动态布局
- url伪静态 重写
- Unity 四元数
- TCP连接探测中的Keepalive 和心跳包
- 输入的字符串格式不正确
- 用C++设计一个不能被继承的类