动态转换的一些“好用”示例是什么? [英] What are some 'good use' examples of dynamic casting?

查看:95
本文介绍了动态转换的一些“好用”示例是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们经常听到/读到应该避免动态转换。我想知道您认为它的好用示例是什么?

We often hear/read that one should avoid dynamic casting. I was wondering what would be 'good use' examples of it, according to you?

编辑:

是的,我知道其他线程:确实是在阅读时

Yes, I'm aware of that other thread: it is indeed when reading one of the first answers there that I asked my question!

推荐答案

该最新线程提供了一个方便使用的示例。有一个基础Shape类,以及从其派生的Circle和Rectangle类。在测试相等性时,很明显,Circle不能等于Rectangle,尝试对其进行比较将是一场灾难。在遍历Shapes的指针集合的同时,dynamic_cast会执行双重任务,告诉您形状是否可比,并为您提供适当的对象进行比较。

This recent thread gives an example of where it comes in handy. There is a base Shape class and classes Circle and Rectangle derived from it. In testing for equality, it is obvious that a Circle cannot be equal to a Rectangle and it would be a disaster to try to compare them. While iterating through a collection of pointers to Shapes, dynamic_cast does double duty, telling you if the shapes are comparable and giving you the proper objects to do the comparison on.

< a href = https://stackoverflow.com/questions/301959/vector-iterator-not-dereferencable>向量迭代器不可取消引用

这篇关于动态转换的一些“好用”示例是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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