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


- C++ 协变模板 2021-01-01
- 静态初始化顺序失败 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 从python回调到c++的选项 2022-11-16