C++强制类型转换操作符 dynamic_cast
1️⃣ 基本概念
- 定义:
dynamic_cast是 C++ 提供的 运行时类型安全的强制类型转换操作符 - 作用:将 基类指针/引用 安全地转换为 派生类指针/引用
- 特点:
- 只适用于 有虚函数的多态类型
- 在运行时进行类型检查,如果转换非法,会返回
nullptr(指针)或抛出std::bad_cast(引用)
2️⃣ 语法
|
dynamic_cast<new_type>(expression) |
|---|
- new_type:目标类型(通常为指针或引用类型)
- expression:要转换的对象(基类指针/引用)
3️⃣ 使用场景
- 多态类型安全下的向下转型(Downcasting)
- 将基类指针转换为派生类指针
- 在运行时保证类型安全
- 类型检查
- 在访问派生类特有成员前,先检查对象类型
- 避免非法转换
- 相比
static_cast,dynamic_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️⃣ 总结
dynamic_cast用于 多态类安全下的类型转换- 常用于 向下转型(Base → Derived)
- 指针失败返回
nullptr,引用失败抛出std::bad_cast - 需要虚函数表支持(即基类有虚函数)
更多推荐
所有评论(0)