① const_cast操作符允许添加或移除表达式中类型的const或volatile修饰符
const Person *getEmployee(){} Person *anEmployee = const_cast<Person *>(getEmployee());
② static_cast它用于将一个继承层次结构中的基类的指针或引用,向下转型为一个派生类的指针或引用。
static_cast操作符用于相对而言可跨平台移植的转型。
Shape *sp = new Circle(); //指向Circle,如果指向其它派生类,如指向Triangle,则下列类型虽能转换,但是会产生运行期错误。 Circle *cp = static_cast<Circle *>(sp)//向下转型 或者执行引用 Circle &cp = static_cast<Circle&>(*sp);
③ dynamic_cast仅用于对多态类型进行向下转型(也就是说,被转型的表达式的类型,必须是一个指向带有虚函数的类类型的指针)。
dynamic_cast通过if(。。。)执行安全期检查。如果是转换为引用,这安全期检查不仅返回NULL ,还会返回异常。
#include "stdafx.h" #include <iostream> using namespace std; class A { public: virtual void func() { cout<<"我是A的func()"<<endl; } }; class B :public A { public: void func() { cout<<"我是B的func()!"<<endl; } }; int _tmain(int argc, _TCHAR* argv[]) { A *a = new B(); //不能执行其它派生类,否则下列转换将返回NULL if( B *b = static_cast<B *>(a)) { b->func(); } else { cout<<"转换失败!"<<endl; } }
④
reinterpret_cast没有太多标准提供的保证,不过它通常的行为可以顾名思义。它从位的角度来看待一个对象,从而允许将一个东西看做另一个完全不同的东西,一致性差。
hopeItWorks = reinterpret_cast<char *>(0x00ff0000); //把int假装成指针
itn *hopeless = reinterpret_cast<int *>(hopeItWorks);//把char* 假装成int*
用 *(unsigned int *)0x12345000=559给绝对地址0x12345000赋值。
用 *((void(*)())0x10000000)()程序跳转到绝对地址0x10000000