什么时候应该在 C++ 中使用 static_cast、dynamic_cast、const_cast 和 reinterpret_cast?
const_cast
可用于删除或添加const到变量。如果需要从变量中添加/删除常量,这会很有用。
static_cast
这用于普通/普通类型转换。这也是负责隐式类型强制的强制转换,也可以显式调用。您应该在将float转换为int、char转换为int等情况下使用它。
dynamic_cast
此强制转换用于处理多态性。只有在转换到派生类时才需要使用它。当您从基类转换到派生类时,这专门用于继承。
reinterpret_cast
这是最难使用的。它用于重新解释位模式,并且级别极低。它主要用于将原始数据位流转换为实际数据或将数据存储在对齐指针的低位之类的事情。