读书笔记:const_cast,reinterpret_cast,static_cast,dynamic_cast
2015-11-13 09:15
363 查看
1、reinterpret_cast
Allows any pointer to be converted into any other pointer type. Also allows any integral type to be converted into any pointer type and vice versa.
样例
2、const_cast
Removes the const, volatile, and __unaligned attribute(s) from a class.
样例:
样例
3、dynamic_cast
可以进行两个方向转换,downcast,upcast, 也就是派生类指针转换成基类指针,也可以基类指针转换成派生类指针。如果基类指针指向的对象地址是派生类对象,那么转换指针非空,否者为NULL.
Allows any pointer to be converted into any other pointer type. Also allows any integral type to be converted into any pointer type and vice versa.
样例
int _tmain(int argc, _TCHAR* argv[]) { CCTest objTest; CCBase *p = (CCBase*)reinterpret_cast<void*>(&objTest); p->SetNumber1(1); //CCBase::SetNumber1 CCTest *p2 = (CCTest*)reinterpret_cast<void*>(&objTest); p2->SetNumber1(1); //CCTest::SetNumber1 unsigned int val = reinterpret_cast<unsigned int>( &objTest ); //objTest的地址 return 0; }
2、const_cast
Removes the const, volatile, and __unaligned attribute(s) from a class.
样例:
int _tmain(int argc, _TCHAR* argv[]) { int a = 12; const int& a1= a; const_cast<int&>(a1) =21; // a:21,移除const常量声明 a1 =12; //Error:“a1”: 不能给常量赋值 return 0; }
样例
class CCTest { public: void SetNumber1(int val) const { const_cast<CCTest*>(this)->number = val; //ok } void SetNumber2(int val) const { number = val; //error C3490: 由于正在通过常量对象访问“number”,因此无法对其进行修改 } private: int number; };
3、dynamic_cast
可以进行两个方向转换,downcast,upcast, 也就是派生类指针转换成基类指针,也可以基类指针转换成派生类指针。如果基类指针指向的对象地址是派生类对象,那么转换指针非空,否者为NULL.
CShape *pShape1 = new CRectangle(); try { CRectangle* p = dynamic_cast<CRectangle*>(pShape1); } catch (std::bad_cast&) { }
相关文章推荐
- 只考虑自己会严重损害智商——北漂18年(32)
- LeetCode Remove Invalid Parentheses
- 浏览器 chrome 360等 加载本地json 或者xml 文件
- 分组查询
- JAVA8中时间的处理
- iOS/Mac&nbsp;OS&nbsp;X&nbsp;汉字转拼音
- 如何使用KeyChain保存和获取UDID
- Objective-C&nbsp;JSON操作
- IOS&nbsp;后台无限执行任务
- IOS&nbsp;Monkey测试UI&nbsp;AutoMonkey
- TestFlight——完美的iOS&nbsp;App测…
- 使用iosMonkey脚本测试iOS应用的稳…
- NSdata&nbsp;与&nbsp;NSString,By…
- &lt;转&gt;Application&nbsp;Loade…
- ios开发过程中碰到的严重bug,修复…
- iOS开发之友盟统计SDK的使用
- 数据结构、算法与应用 (C++描述) 第二版 1.1
- sql按月统计数据
- 整而难“合” 广汽大自主迷局待解
- setTimeout 0