What are some #39;good use#39; examples of dynamic casting?(什么是动态转换的“好用示例?)
问题描述
我们经常听到/读到应该避免动态转换.我想知道根据你的说法,什么是它的好用"示例?
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.
向量迭代器不可解引用
这篇关于什么是动态转换的“好用"示例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:什么是动态转换的“好用"示例?
基础教程推荐
- c++ STL设置差异 2022-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 提升 ASIO 流缓冲 2021-01-01
