1. static_cast<>
- 可以转换内置数据类型;
- 不可以转换没有关系的指针或引用;
- 可以转换有继承关系的指针或引用(父类转子类或子类转父类都可以);
// static_cast<>
// 1. 内置对象
int a = 97;
char c = static_cast<char>(a); // OK
cout << c << endl;
// 2. 自定义类型对象
// Building bb;
// Animal aa = static_cast<Animal>(bb); // error: no matching function for call to ‘Animal::Animal(Building&)’
// 3. 不同类型的指针转换
// int *p = &a;
// char *pc = static_cast<char*>(p); // error: invalid static_cast from type ‘int*’ to type ‘char*’
// cout << pc << endl;
// Animal * pa = NULL;
// Building *pb = static_cast<Building*>(pa); // error: invalid static_cast from type ‘Animal*’ to type ‘Building*’
// 4. 有继承关系的指针或引用
Animal * pa = NULL;
Cat *pc = static_cast<Cat*>(pa); // OK
pa = static_cast<Animal*>(pc); // OK
2. dynamic_cast<>
- 只能转换有继承关系的指针或引用,且只能将子类转为父类(从大到小),因为将父类转为子类会不安全(从小到大)
// dynamic_cast<>
// 1. 内置对象
// c = dynamic_cast<char>(a); // error: cannot dynamic_cast ‘a’ (of type ‘int’) to type ‘char’ (target is not pointer or reference)
// 2. 非继承关系指针
// Building *pb = dynamic_cast<Building*>(pa); // error: cannot dynamic_cast ‘pa’ (of type ‘class Animal*’) to type ‘class Building*’ (source type is not polymorphic)
// 3. 继承关系指针会做安全检查,只能将子类指针转为父类指针
// pc = dynamic_cast<Cat*>(pa); // error: cannot dynamic_cast ‘pa’ (of type ‘class Animal*’) to type ‘class Cat*’ (source type is not polymorphic)
pa = dynamic_cast<Animal*>(pc); // OK
3. const_cast<>
- 只能转换指针或引用类型,添加或去除
const
修饰 - 非
const
的可以直接转为const
类型,但反之不行
int i = 0;
int *a = &i
const int* b = const_cast<const int*>(a);
const int* bb = a; // OK
a = const_cast<int*>(b); // OK
a = b; // error: invalid conversion from ‘const int*’ to ‘int*’ [-fpermissive]
4. reinterpret_cast<>
对任何类型的指针进行强制转换,包括函数指针