C++提供了四种显示的类型转换函数reinterpret_cast const_cast static_cast dynamic_cast。前三种在编译时进行转换,最后一种在运行时进行转换。
******_cast<new_type>(expression);
reinterpret_cast将一个类型的指针,转换为另一个类型的指针,或者将指针值转换为一个整型数,不能用于非指针类型的转换。
double d=9.3;
double * pd=&d;
int *pi=reinterpret_cast<int *>(pd);
class A{};
class B{};
A *pa=new A();
B* pb=reinterpret_cat<B*>(pa);//相当于隐式转换B* pb=(B*)pa;
long j=reinterpret_cast<long>(pi);//相当于隐式转换long j=(long)pi;
与隐式转换一样,const指针无法转换为void指针。
const_cast类型转换函数用于消除指针变量的常量属性,将它转换为一个对应指针类型的普通变量,反过来也可以。
const int *pi=3.14;
int *pj=const_cast<int*>(pi);
const int*pk=const_cast<const int*>(pi);
static_cast主要用于基本类型之间和具有继承关系之间的类型之间的转换。可以将基类和继承类的指针进行互换,但无法将非指针继承类转化为基类或其它无继承关系的类。
int i=0;
double j=static_cast<double>(i);
base * pb=new base;
Derived* pd=static_cast<Derived *>(pb);
dynamic_cast 与static_cast相对,在运行时进行转换分析,只能在继承类的指针之间和引用之间进行转换,进行转换时会根据挡墙运行时类型信息(Run-Time Type Indentification),判断类型之间的转换是否合法;指针转换失败可通过判断是否为null指针进行检测,如果引用转换失败则抛出bad_cast异常。可以用于检测内存对象的类型信息。
工程-设置--c++-C++Language 勾选允许运行时类型信息RTTI