总结
- static_cast:基本类型转换,低风险;
- dynamic_cast:类层次间的上行转换或下行转换,低风险;
- const_cast:去 const 属性,低风险;
- reinterpret_cast:转换不相关的类型,高风险。
详细说明
-
const_cast:修改const属性,用于指针和引用,可添加或删除const。
示例:
const int num = 10; int* non_const_ptr = const_cast<int*>(&num);
-
static_cast:静态类型转换,用于基本数据类型、继承关系中的向上转换,空指针转换。
示例:
double d = 3.14; int i = static_cast<int>(d); class Base { /*... */ }; class Derived : public Base { /*... */ }; Base* base_ptr = new Derived; Derived* derived_ptr = static_cast<Derived*>(base_ptr);
-
dynamic_cast:动态类型转换,用于基类和子类之间的转换,要求有虚函数,不安全则返回NULL。
示例:
class Base { virtual void foo() {} }; class Derived : public Base { /*... */ }; Base* base_ptr = new Derived; Derived* derived_ptr = dynamic_cast<Derived*>(base_ptr); if (derived_ptr) { // 转换成功 } else { // 转换失败 }
-
reinterpret_cast:底层数据重新解释,用于指针、引用、算术类型等,不保证类型安全。
示例:
int num = 42; double* ptr = reinterpret_cast<double*>(&num);
虽然类型转换是一种有用的工具,但在项目中应慎用,并确保它们不会引入潜在的错误或不安全的操作。良好的代码设计和类型安全性是更重要的目标。