static_cast
在编译期间确定类型转换,不保证安全性
程序员要自己保证转换的安全性
dynamic_cast
运行时类型检查, 有额外的运行时开锁
保证安全性, 在不能转换时返回 nullptr
无法使用 dynamic_cast 的情况
- dynamic_cast 需要运行时类型信息(RTTI, run-time type identification), 所以无虚方法的子类父类无法使用 dynamic_cast 转换
- 对于非公有的继承关系 dynamic_cast 会 fail 并返回 nullptr
- 存在 dreaded diamond 继承关系的情况下,编译不通过, 比如以下情况,将 TA 转为 Person会报错:'Person' is an ambiguous base of 'TA'
const_cast
对一个变量添加或去除 const 属性
reinterpret_cast
最危险的 cast, 可以理解为直接改变了编译器对相应地址的解释方式
父子类换转场景总结
可选方案 | |
无虚方法子类父类的相互转换 | 1. c 式强转 2. static_cast |
有虚方法父类子类相互转换 | 1. c 式强转 2. static_cast 3. dynamic_cast |