C语言
int i = 1;
double d = 1.5;
int d2 = (int)d;
double i2 = (double)i;
C++
static_cast
- 可以完全代替C语言的基本类型转换
- 可以父子类指针互相转换,如果两个类不相关,则无法转换
class Base(){};
class Derived:public Base{};
int i = 1;
double d = 1.5;
int D1 = static_cast<int>(d);
double D2 = static_cast<double>(i);
Base * b1 = new Base;
Base * b2 = new Derived;
Derived * B1 = static_cast<Derived *>(b1);
Derived * B2 = static_cast<Derived *>(b2);
dynamic_cast
- 只能用于对象指针之间的转换
- 可以父子类指针互相转换,转换结果也可以是引用
- 在将父类指针转换为子类指针的过程中,需要对背后的对象类型进行检查,以保证完全匹配
class Base{virtual void my(){} };
class Derived:public Base{};
Base *b1 = new Base;
Base *b2 = new Derived;
Derived *B1 = dynamic_cast<Derived *>(b1);
Derived *B2 = dynamic_cast<Derived *>(b2);
Derived &b3 = dynamic_cast<Derived &>(*b1);
Derived &b4 = dynamic_cast<Derived &>(*b2);
const_cast
class Test{};
const Test * t1 = new Test;
Test * t2 = const_cast<Test *>(t1);
reinterpret_cast
- 可以将一种类型的指针直接转换为另一种类型的指针,不论两个类型之间什么关系
- 可以将指针与整数之间互相转换
- 常用在不同函数指针之间的转换
class A{};
class B{};
A * a = new A;
B * b = reinterpret_cast<B *>(a);