const_cast<type-id>(expression)
2016-10-29 19:17
309 查看
//**********************// 类类型 class B{ public: int m_num; B():m_num(50){} }; void foo(void) { const B* b1 = new B(); B* b2 = const_cast<B*>(b1); b2->m_num = 200; cout <<"b1:" << b1->m_num << endl;//200 cout <<"b2:" << b2->m_num << endl;//200 const B b3; B b4 = const_cast<B&>(b3); b4.m_num = 300; cout << "b3:" << b3.m_num << endl;//50 cout << "b4:" << b4.m_num << endl;//300 } //************************//
//************************// 基本类型 void foo(){ const int a = 100; int* p1 = const_cast<int*>(&a); *p1 = 200; cout << *p1 << endl;//200 cout << a << endl;//100 const int* p2 = new int(100); int* p3 = const_cast<int*>(p2); *p3 = 200; cout << *p2 << endl;//200 cout << *p3 << endl;//200 } //************************//你会发现:
A:可以为基本类型或者类类型;
const A a;随便怎么修改a都不会变化
const A* p = new A();去掉p的const属性后,*p就变化了.
//*****************// class A{ public: A(){ m_num=1; } int m_num; }; void foo (void){ A a; const A &r = a; A a1 = const_cast<A&>(a); a1.m_num = 200; cout << a1.m_num << endl;//200 cout << a.m_num << endl;//1 } //****************//
const_cast<type-id>(expression)中,type-id只能为指针或引用,其他的都错,这个表达式即可以去除
expression中的const属性或volatil属性,还能增加const属性或者volatil属性
const int i = 10;
int i1 = const_cast<int>(i) //错误
增加const属性与volatil属性相反.
相关文章推荐
- const_cast<type_id> (expression)
- C++ 笔记 dynamic_cast < type-id > ( expression )
- static_cast < type-id > ( expression ) http://blog.csdn.net/moruihong/article/details/7712260
- C++类型转换运算符之const_cast<newtype>(expression)
- reinterpret_cast < type-id > ( expression ) 表达式
- static_cast < type-id > ( expression )与reinterpret_cast<type-id> (expression)的区别
- dynamic_cast<type-id>(expression)
- dynamic_cast < type-id > ( expression )
- c++11 使用c++风格的cast: static_cast<type>(expression) const_cast<type> dynamic_cast reinterpret_cast
- Assigning to 'id<QMapViewDelegate>" from incompatible type "view control * const_strong"
- dynamic_cast <new_type> (expression)
- Assigning to 'id<UITextViewDelegate>' from incompatible type 'HBComposeViewController *const __stron
- Sending 'ViewController *const __strong' to parameter of incompatible type 'id<***Delegate>'
- c++ 之 reinterpret_cast <new_type> (expression) 常见用法
- typeid, const_cast<Type>的使用
- Assigning to "id<CALayerDelegate> _Nullable" from incompatible type "ZXCapture *const __strong" 的警告提示信息
- Sending 'ViewController *const __strong' to parameter of incompatible type 'id<***Delegate>'
- C++类型转换关键字 *_cast<type> (expression)
- Assigning to 'id<xxxxDelegate>' from incompatible type 'xxxxViewController *const __strong'
- Xcode编译警告Assigning to 'id<XXXDelegat> ——Nullable' from incompatible type 'XXXView *const_strong'