reinterpret_cast 和 static_cast 的区别

安全性:

static_cast 是一个安全的类型转换,它只能转换具有继承关系或密切相关的类型,并且在编译时进行类型检查。

reinterpret_cast 是一个不安全的类型转换,它可以将任何类型的指针转换为任何其他类型的指针,而无需考虑类型安全性。

用途:

static_cast 用于转换具有继承关系或密切相关的类型,例如基类和派生类、整数类型和浮点类等。

reinterpret_cast 用于转换不相关的类型,例如指针类型和整数类型、结构体和联合体等。

使用场景

static_cast

  • 从基类转换为派生类
  • 从派生类转换为基类
  • 从整数类型转换为浮点类型
  • 从浮点类型转换为整数类型
  • 从枚举类型转换为整数类型

reinterpret_cast

  • 将指针类型转换为整数类型
  • 将整数类型转换为指针类型
  • 将结构体转换为联合体
  • 将联合体转换为结构体
  • 将函数指针转换为 void* 类型
  • 将 void* 类型转换为函数指针

示例

static_cast

复制代码
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

复制代码
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 时需要格外小心,因为它可能会导致未定义的行为或程序崩溃,如果转换的类型不兼容!

相关推荐
西西弗Sisyphus2 个月前
C++ 类型转换 包括C风格的转换、static_cast、const_cast、reinterpret_cast、dynamic_cast、模板特化等
c语言·c++·模板特化·static_cast·const_cast·reinterpret·dynamic_cast