1️⃣ 基本概念

  • 定义dynamic_cast 是 C++ 提供的 运行时类型安全的强制类型转换操作符
  • 作用:将 基类指针/引用 安全地转换为 派生类指针/引用
  • 特点
    1. 只适用于 有虚函数的多态类型
    2. 在运行时进行类型检查,如果转换非法,会返回 nullptr(指针)或抛出 std::bad_cast(引用)

2️⃣ 语法

dynamic_cast<new_type>(expression)

  • new_type:目标类型(通常为指针或引用类型)
  • expression:要转换的对象(基类指针/引用)

3️⃣ 使用场景

  1. 多态类型安全下的向下转型(Downcasting)
    • 将基类指针转换为派生类指针
    • 在运行时保证类型安全
  2. 类型检查
    • 在访问派生类特有成员前,先检查对象类型
  3. 避免非法转换
    • 相比 static_castdynamic_cast 提供运行时检查,防止段错误

4️⃣ 使用示例

4.1 类定义

#include <iostream>

#include <typeinfo>

using namespace std;

class Base {

public:

virtual ~Base() {}

};

class Derived : public Base {

public:

void show() { cout << "Derived class function" << endl; }

};

4.2 指针转换示例

Base* base = new Derived;  // 基类指针指向派生类对象

Derived* derived = dynamic_cast<Derived*>(base);

if (derived) {

derived->show();  // 成功,输出 "Derived class function"

} else {

cout << "转换失败" << endl;

}

4.3 非法转换示例

Base* base2 = new Base;  // 基类对象

Derived* derived2 = dynamic_cast<Derived*>(base2);

if (derived2 == nullptr) {

cout << "转换失败" << endl;  // 输出

}

4.4 引用转换示例

try {

Base& baseRef = *base2;

Derived& derivedRef = dynamic_cast<Derived&>(baseRef);

} catch (bad_cast& e) {

cout << "引用转换失败: " << e.what() << endl;

}


5️⃣ 注意事项

注意点

说明

必须有虚函数

dynamic_cast 仅对多态类型有效

指针转换失败返回 nullptr

适用于指针类型向下转型

引用转换失败抛出异常

适用于引用类型向下转型

不适用于非多态类

编译器无法进行运行时类型检查

性能开销

需要 RTTI 支持,运行时有一定开销


6️⃣ 总结

  1. dynamic_cast 用于 多态类安全下的类型转换
  2. 常用于 向下转型(Base → Derived)
  3. 指针失败返回 nullptr,引用失败抛出 std::bad_cast
  4. 需要虚函数表支持(即基类有虚函数)

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐