虚拟函数的行为类似于动态转换
Bjarne 在 联合攻击机 C++ 编码标准 中指出:
向下转换(从基类到派生类的转换)只能是 通过以下机制之一允许:
- 虚拟函数的行为类似于动态转换(最有可能在 相对简单的情况)
- 使用访问者(或类似)模式(最有可能在 复杂的情况)
我无法理解第一个命题。谷歌搜索没有给出任何例子,也没有解释。
虚函数如何像动态强制转换一样起作用?
In JOINT STRIKE FIGHTER AIR VEHICLE C++ CODING STANDARDS Bjarne states, that:
Down casting (casting from base to derived class) shall only be
allowed through one of the following mechanism:
- Virtual functions that act like dynamic casts (most likely useful in
relatively simple cases)- Use of the visitor (or similar) pattern (most likely useful in
complicated cases)
I can't wrap my head around first proposition. Googling it presented no examples, nor explanation.
How can virtual function act like a dynamic cast?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它指的是一种在 C++ 早期很常见的技术,当时
dynamic_cast
、RTTI
等被添加到该语言中。基本思想如下所示:
这使您可以对指针执行类似
dynamic_cast
的操作,如果被指针对象实际上属于该类型,则生成指向预期类型的指针,否则生成 <代码> nullptr 。但这有明显的缺点。所涉及的每个类都必须了解其他所有类。添加新类意味着向每个类添加新功能。除非整个类结构是完全静态的(并且只有少量类),否则这很快就会变成维护噩梦。
参考
此技术在《Effective C++》第 1 版第 39 条中有所介绍。我还没有进行确认,但它可能已从较新的版本中删除,因为(至少在大多数人看来)程序员)添加
dynamic_cast
使其过时(充其量)。It's referring to a technique that was kind of common in the early days of C++, before
dynamic_cast
,RTTI
, etc., were added to the language.The basic idea looks something like this:
This lets you do something just about like a
dynamic_cast
on a pointer, yielding a pointer to the expected type if the pointee object is actually of that type, and otherwise anullptr
.This has obvious disadvantages though. Every class involved has to be aware of every other class. Adding a new class means adding a new function to every class. Unless the entire class structure is quite static (and a small number of classes altogether), this can quickly turn into a maintenance nightmare.
Reference
This technique was covered in Effective C++, 1st Edition, Item 39. I haven't checked to be sure, but it was probably dropped from the newer editions, as (at least in the minds of most programmers) the addition of
dynamic_cast
rendered it obsolescent (at best).您可以使用虚函数进行向下转换,如下所示:
在实践中不经常使用。
You can use a virtual function to downcast like this:
Not often used, in practice.