如何使用 dynamic_cast 运算符识别失败的转换? [英] How to identify failed casts using dynamic_cast operator?

查看:33
本文介绍了如何使用 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 运算符识别失败的转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆