C++ 中虚拟会员的目的是什么?
除了安全之外,我看不到虚拟成员在班级中的用途。在设计实现时还有其他使用虚拟的原因吗?编辑:我删除了变量部分。
I don't see the purpose of a virtual member in a class other than safety. Are there any other reasons to use virtual when designing implementations? Edit: I erased the variable part.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不存在虚拟变量,只有虚拟函数或虚拟继承。因此,缺乏这样的事情的目的似乎是一件好事。
编辑:虚函数是 C++ 实现运行时多态性的方式。试图解释多态性的用途/目的可能有点超出了合理大小的帖子的范围。然而,一般的想法是,您可以在基类中定义某种类型的行为,然后在每个派生类中以不同的方式实现该行为。对于比大多数例子更实际的示例,请考虑一个数据库基类,它定义了诸如查找符合某些条件的一组记录之类的内容。然后,您可以使用 SQL 数据库(通过生成 SQL)以一种方式实现该行为,而使用 MongoDB 等方式实现另一种方式。其中一个的实现与另一个有很大不同,但从抽象的角度来看,它们仍然在做相同的基本事情(查找/读取/写入记录)。
There is no such thing as a virtual variable, only a virtual function or virtual inheritance. As such, lack of a purpose for such a thing seems like rather a good thing.
Edit: Virtual functions are how C++ implements run-time polymorphism. Trying to explain the uses/purposes of polymorphism is probably a bit beyond what will fit into a reasonable-sized post. The general idea, however, is that you can define some type of behavior in a base class, then implement that behavior differently in each derived class. For a more practical example than most, consider a base
database
class that defines things like finding a set of records that fit some criteria. Then you can implement that behavior one way with a SQL database (by generating SQL), and another with, say, MongoDB. The implementation for one will be quite a bit different from the other, but viewed abstractly they're still both doing the same basic things (finding/reading/writing records).我将回答......用代码!
I shall answer... In code!