找回密码
 立即注册
首页 业界区 安全 C++ 强制类型转化

C++ 强制类型转化

毁抨句 前天 09:16
C++ 提供了四种显式强制类型转换运算符(static_cast、dynamic_cast、const_cast、reinterpret_cast),相比 C 风格的强制转换((类型)表达式),它们更具针对性、可读性和安全性,能让转换意图更清晰,且编译器可提供更严格的检查。
1、static_cast - 静态转换

用于编译器可在编译时确定安全性的转换,不涉及运行时类型检查,是最常用的转换方式。
语法:static_cast(源表达式)
1.1 基本数据类型转换(如数值类型之间的转换)
  1. int a = static_cast<int>(3.14);  // double → int(截断小数)
  2. double b = static_cast<double>(a);  // int → double
复制代码
1.2 非 const 类型之间的转换(如派生类与基类的向上转型)
  1. class Base {};
  2. class Derived : public Base {};
  3. Derived d;
  4. Base* b_ptr = static_cast<Base*>(&d);  // 派生类指针 → 基类指针(向上转型,安全)
复制代码
1.3 空指针转换为目标类型指针
  1. int* p = static_cast<int*>(nullptr);  // 空指针 → int* 空指针
复制代码
1.4 显式触发隐式转换

将 void* 转换为具体类型指针
  1. void* void_ptr = new int(10);
  2. int* int_ptr = static_cast<int*>(void_ptr);  // void* → int*(需确保类型匹配)
复制代码
1.5 危险用法警示
  1. // 危险:不相关指针转换
  2. double* pd = new double(3.14);
  3. int* pi = static_cast<int*>(pd); // 编译错误!static_cast禁止不相关指针转换
  4. // 正确做法:使用reinterpret_cast(但需谨慎)
  5. int* pi2 = reinterpret_cast<int*>(pd);
  6. // 向下转型(基类 → 派生类)时不检查类型安全性,可能导致未定义行为
  7. Base b;
  8. Derived* d_ptr = static_cast<Derived*>(&b);  // 编译通过,但运行时访问 d_ptr 可能崩溃
复制代码
2、dynamic_cast - 动态转换

用于多态场景下的类型转换(主要是向下转型),依赖虚函数表(vtable)在运行时检查类型兼容性,是唯一具有运行时检查能力的转换。
语法:dynamic_cast(源表达式)
转换规则:

  • 向上转型(派生类 → 基类)
    与 static_cast 效果相同,总是成功。
  • 向下转型(基类 → 派生类)

    • 若源指针 / 引用实际指向的对象类型与目标类型匹配,则转换成功。
    • 若不匹配:指针转换返回 nullptr,引用转换抛出 std::bad_cast 异常。

[code]class Base { public: virtual ~Base() {} }; // 必须有虚函数!class Derived : public Base { public: void derivedFunc() {} };Base* bPtr = new Derived; // 实际指向一个Derived对象// 安全的下行转换Derived* dPtr = dynamic_cast(bPtr);if (dPtr != nullptr) { // 必须检查是否转换成功!    dPtr->derivedFunc(); // 安全调用}// 对于引用,失败会抛出 std::bad_cast 异常try {    Derived& dRef = dynamic_cast(*bPtr);    dRef.derivedFunc();} catch (const std::bad_cast& e) {    std::cerr

相关推荐

您需要登录后才可以回帖 登录 | 立即注册