How to identify failed casts using dynamic_cast operator?(如何使用 dynamic_cast 运算符识别失败的转换?)
问题描述
Scott Meyer 在他的 Effective C++ 一书中说 dynamic_cast 用于执行向下或跨继承层次结构的安全转换.也就是说,您使用 dynamic_cast 将指向基类对象的指针或引用转换为指向派生或同级基类对象的指针或引用,这样您就可以确定转换是否成功.
Scott Meyer in his book Effective C++ says dynamic_cast is used to perform safe casts down or across an inheritance hierarchy. That is, you use dynamic_cast to cast pointers or references to base class objects into pointers or references to derived or sibling base class objects in such a way that you can determine whether the casts succeeded.
失败的转换由空指针(转换指针时)或异常(转换引用时)指示.
Failed casts are indicated by a null pointer (when casting pointers) or an exception (when casting references).
我想得到两个代码片段,显示在转换指针和转换引用的情况下失败的转换.
I would like to get two code snippet showing the failed cast in the case of casting pointer and casting reference can be indicated.
推荐答案
对于指针,它是一个简单的空检查:
For pointers, it's a simple null check:
A* a = new A();
B* b = dynamic_cast<B*>(a);
if (b == NULL)
{
// Cast failed
}
对于参考,你可以抓住:
For references, you can catch:
try {
SomeType &item = dynamic_cast<SomeType&>(obj);
}
catch(const std::bad_cast& e) {
// Cast failed
}
这篇关于如何使用 dynamic_cast 运算符识别失败的转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 dynamic_cast 运算符识别失败的转换?
基础教程推荐
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- c++ STL设置差异 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
