动态铸造有多糟糕? [英] How bad is dynamic casting?

查看:128
本文介绍了动态铸造有多糟糕?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们经常听到/读到应该避免动态铸造。

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。在测试平等时,很明显,一个圆不能等于一个矩形,尝试比较它们是一个灾难。在迭代通过指向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 =http://stackoverflow.com/questions/301959/vector-iterator-not-dereferencable>矢量迭代器不可解除

Vector iterator not dereferencable

这篇关于动态铸造有多糟糕?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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