C++ 中的四种类型转换是 C++ 引入的更安全、更明确的类型转换操作符,相比 C 风格的强制转换更加精细和可控:
- static_cast - 静态类型转换
最常用的转换,用于良性转换
cpp
int i = 10;
double d = static_cast<double>(i); // 基本类型转换
class Base {};
class Derived : public Base {};
Base* b = new Derived();
Derived* d = static_cast<Derived*>(b); // 向下转换(不安全,不检查)
int* p = nullptr;
void* vp = static_cast<void*>(p); // void* 转换
- dynamic_cast - 动态类型转换
用于多态类型的向下转换,运行时检查类型安全
cpp
class Base { virtual void foo() {} };
class Derived : public Base {};
Base* b = new Derived();
// 安全的向下转换
Derived* d = dynamic_cast<Derived*>(b);
if (d != nullptr) { // 转换成功
// 使用 d
}
// 转换失败返回 nullptr(对指针)或抛出异常(对引用)
- const_cast - 常量性转换
添加或移除 const、volatile 属性
cpp
const int ci = 10;
int* pi = const_cast<int*>(&ci); // 移除 const
*pi = 20; // 未定义行为,ci 原本是 const
void print(char* str) { /* 修改 str */ }
const char* s = "hello";
print(const_cast<char*>(s)); // 临时移除 const
- reinterpret_cast - 重新解释转换
低级别的重新解释,最危险的转换
cpp
int* p = new int(65);
char* c = reinterpret_cast<char*>(p); // 重新解释指针类型
int i = 0x12345678;
float f = reinterpret_cast<float&>(i); // 二进制重新解释
// 函数指针转换
typedef void (*FuncPtr)();
FuncPtr func = reinterpret_cast<FuncPtr>(0x12345678);

