目录
每种类型转换操作符都有其特定的应用场景和限制,应根据实际需求选择合适的转换方式。特别是
reinterpret_cast,由于它的类型安全性很低,使用时需格外小心。

1.static_castint 转为 double)、父类与子类之间的转换(在继承关系中,但不涉及多态)、以及空指针和空类型之间的转换。static_cast(expression) - double d = 3.14;
- int i = static_cast<int>(d); // d 被转换为 3
2.dynamic_castpolymorphic)类型之间的转换。nullptr,引用转换抛出 std::bad_cast 异常。dynamic_cast(expression) - class Base {
- virtual void func() {}
- };
- class Derived : public Base {};
- Base* basePtr = new Derived;
- Derived* derivedPtr = dynamic_cast<Derived*>(basePtr); // 成功转换
3.const_castconst 或 volatile 属性。它是唯一可以移除 const 限制的转换方式。const 限定,尝试修改被 const 限定的变量会导致未定义行为。const_cast(expression) - const int* p = new int(10);
- int* modifiable = const_cast<int*>(p); // 移除了 `const` 属性
4.reinterpret_castreinterpret_cast(expression) - int* p = new int(65);
- char* ch = reinterpret_cast<char*>(p); // 将 int 指针转换为 char 指针