如何使用dynamic

系统教程 行业动态 更新时间:2024-06-14 16:57:40
如何使用dynamic_cast运算符来识别失败的转换?(How to identify failed casts using dynamic_cast operator?)

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.

最满意答案

对于指针,这是一个简单的空检查:

A* a = new A(); B* b = dynamic_cast<B*>(a); if (b == NULL) { // Cast failed }

对于参考,你可以看到:

try { SomeType &item = dynamic_cast<SomeType&>(obj); } catch(const std::bad_cast& e) { // Cast failed }

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 }

更多推荐

本文发布于:2023-04-13 12:09:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/f6d2b8b2e4c45d5f6cfcbbf64d075a3d.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   dynamic

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!