1. static_cast
static_cast<new_type>(expression)相当于传统的C语言里的强制转换,该运算符把expression转换为new_type类型,用来强迫隐私转换 主要用于一下几种用法 1.用于类层次结构中基类和派生类之间指针或者引用的转换 Base* bp = static_cast<Derived*>(dp) 2.用于基本数据类型之间的转换,int->char char a = 'a'; int b = static_cast<int>(a); int e = 10; const int f = static_cast<const int>(e); 3.把空指针转换成目标类型的空指针 double *c = new double; void *d = static_cast<void*>(c); 4.把任何类型的表达式转换成void类型 double *c = new double; void *d = static_cast<void*>(c); const int g = 20; int *h = static_cast<int*>(&g) //编译错误,不能转换掉g的const属
2. dynamic_cast
dynamic_cast<type*>(e) dynamic_cast<type&>(e) dynamic_cast<type&&>(e) 该type必须是一个类类型,在第一种形式中,type必须是一个有效的指针,在第二种形式中type必须是一个左值;在第三种形式中,type必须是一个右值。e的类型必须符合以下三个条件中的任何一个:e的类型是目标类型type的共有派生类、e的类型是目标type的公有基类或者是目标type的类型。如果一条dynamic_cast语句转换失败了,则结果为0。如果转换目标是引用类型并且失败了,则抛出一个std::bad_cast异常 1.指针类型 // bp是指向Base的指针,现在转换成指向Derived的指针, if(Derived *dp = dynamic_cast<Derived *>(bp)) //失败返回0 { } 2.引用类型 //因为不存在所谓空引用,所以引用类型的dynamic_cast转换与指针类型不同,在失败是会抛出std::bd_cast异常 void f(const Base &b){ try{ const Derived &d = dynamic_cast<const Derived &>(b); } } 3. const_cast
const_cast,用于修改类型的const或者volatile属性 1.常量指针被转化为非常量的指针,并且仍然指向原来的对象 const char* g = "hello"; char *h = const_cast<char *>g; 2.常量引用被转为非常量的引用,并且仍然指向原来的对象 const int g = 20; int &h = const_cast<int&>(g); 3.const_cast一般用于修改底指针。如const char *P形式
4. reinterpret_cast
new_type必须是一个指针,引用、算数类型、函数指针或者成员指针。它可以把一个指针转换成和一个整数,也可以把一个整数转成一个指针。 int otput(int p){ cout<<p<<endl; return 0; } typeded int (*test_func)(int); //定义函数指针test_func int main(){ int p = 10; test_func fun1 = output; fun1(p); test_fun fun2 = reinterpret_cast<test_func>(&p); fun2(p); //将整数类型转换成函数指针后,vc++在执行过程中会报"...中的 0xxxxxxxxx 处有未经处 //理的异常: 0xC0000005: Access violation"错误: return 0; }