reinterpret_cast 和 static_cast 的区别
安全性:
static_cast
是一个安全的类型转换,它只能转换具有继承关系或密切相关的类型,并且在编译时进行类型检查。
reinterpret_cast
是一个不安全的类型转换,它可以将任何类型的指针转换为任何其他类型的指针,而无需考虑类型安全性。
用途:
static_cast
用于转换具有继承关系或密切相关的类型,例如基类和派生类、整数类型和浮点类等。
reinterpret_cast
用于转换不相关的类型,例如指针类型和整数类型、结构体和联合体等。
使用场景
static_cast
- 从基类转换为派生类
- 从派生类转换为基类
- 从整数类型转换为浮点类型
- 从浮点类型转换为整数类型
- 从枚举类型转换为整数类型
reinterpret_cast
- 将指针类型转换为整数类型
- 将整数类型转换为指针类型
- 将结构体转换为联合体
- 将联合体转换为结构体
- 将函数指针转换为 void* 类型
- 将 void* 类型转换为函数指针
示例
static_cast
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | class Base { public : virtual void print() { std::cout << "Base" << std::endl; } }; class Derived : public Base { public : void print() override { std::cout << "Derived" << std::endl; } }; int main() { Base* base = new Derived(); Derived* derived = static_cast <Derived*>(base); // 安全的类型转换 derived->print(); // 输出:Derived return 0; } |
reinterpret_cast
1 2 3 4 | int * ptr = new int (10); void * voidPtr = reinterpret_cast < void *>(ptr); // 不安全的类型转换 int * newPtr = reinterpret_cast < int *>(voidPtr); // 不安全的类型转换 std::cout << *newPtr << std::endl; // 输出:10 |
需要注意的是,在使用 reinterpret_cast
时需要格外小心,因为它可能会导致未定义的行为或程序崩溃,如果转换的类型不兼容!
本文来自博客园,作者:{Justin_Hu},转载请注明原文链接:{https://www.cnblogs.com/gchenghu/}
· [翻译] 为什么 Tracebit 用 C# 开发
· 腾讯ima接入deepseek-r1,借用别人脑子用用成真了~
· Deepseek官网太卡,教你白嫖阿里云的Deepseek-R1满血版
· DeepSeek崛起:程序员“饭碗”被抢,还是职业进化新起点?
· RFID实践——.NET IoT程序读取高频RFID卡/标签