C++ 提供了四种显式强制类型转换运算符 (static_cast、dynamic_cast、const_cast、reinterpret_cast),相比 C 风格的强制转换((类型)表达式),它们更具针对性、可读性和安全性,能让转换意图更清晰,且编译器可提供更严格的检查。
1、static_cast - 静态转换
用于编译器可在编译时确定安全性 的转换,不涉及运行时类型检查,是最常用的转换方式。
语法:static_cast(源表达式)
1.1 基本数据类型转换(如数值类型之间的转换)
int a = static_cast<int>(3.14); // double → int(截断小数) double b = static_cast<double>(a); // int → double 复制代码 1.2 非 const 类型之间的转换(如派生类与基类的向上转型)
class Base {}; class Derived : public Base {}; Derived d; Base* b_ptr = static_cast<Base*>(&d); // 派生类指针 → 基类指针(向上转型,安全) 复制代码 1.3 空指针转换为目标类型指针
int* p = static_cast<int*>(nullptr); // 空指针 → int* 空指针 复制代码 1.4 显式触发隐式转换
将 void* 转换为具体类型指针void* void_ptr = new int(10); int* int_ptr = static_cast<int*>(void_ptr); // void* → int*(需确保类型匹配) 复制代码 1.5 危险用法警示
// 危险:不相关指针转换 double* pd = new double(3.14); int* pi = static_cast<int*>(pd); // 编译错误!static_cast禁止不相关指针转换 // 正确做法:使用reinterpret_cast(但需谨慎) int* pi2 = reinterpret_cast<int*>(pd); // 向下转型(基类 → 派生类)时不检查类型安全性,可能导致未定义行为 Base b; 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
相关推荐