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 运算符识别失败的转换?


基础教程推荐
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 这个宏可以转换成函数吗? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 在 C++ 中计算滚动/移动平均值 2021-01-01