重写方法时 virtual 关键字意味着什么?
重写方法时关键字virtual有什么作用?我没有使用它,一切正常。
每个编译器在这方面的行为都相同吗?
我应该使用它还是不应该使用它?
What does the keyword virtual do when overriding a method? I'm not using it and everything works fine.
Does every compiler behave the same in this regard?
Should I use it or not?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果没有它,您就无法重写成员函数。
您只能隐藏一个。
Derived::foo
不覆盖Base::foo
;它只是隐藏它,因为它具有相同的名称,因此以下内容:调用
Derived::foo
。virtual
启用多态性,以便您实际上重写函数:这会调用
Derived::foo
,因为现在 >overridesBase::foo
— 你的对象是多态的。(由于切片问题<,您还必须为此使用引用或指针/a>.)
Derived::foo
不需要重复virtual
关键字,因为Base::foo
已经使用了它。这是由标准保证的,您可以信赖。然而,一些人认为为了清楚起见最好保留这一点。You cannot override a member function without it.
You can only hide one.
Derived::foo
does not overrideBase::foo
; it simply hides it because it has the same name, such that the following:invokes
Derived::foo
.virtual
enables polymorphism such that you actually override functions:This invokes
Derived::foo
, because this now overridesBase::foo
— your object is polymorphic.(You also have to use references or pointers for this, due to the slicing problem.)
Derived::foo
doesn't need to repeat thevirtual
keyword becauseBase::foo
has already used it. This is guaranteed by the standard, and you can rely on it. However, some think it best to keep that in for clarity.基类中的虚拟方法将在层次结构中级联,使具有相同签名的每个子类方法也成为虚拟方法。
如果仅用于文档目的,我建议编写
virtual
。A
virtual
method in the base class will cascade through the hierarchy, making every subclass method with the same signature alsovirtual
.I'd recommend writing the
virtual
though, if for documentation purpose only.当一个函数是虚拟的时,它在整个层次结构中仍然是虚拟的,无论您是否每次都明确指定它是虚拟的。重写方法时,使用 virtual 以便更明确 - 没有其他区别:)
When a function is virtual, it remains virtual throughout the hierarchy, whether or not you explicitly specify each time that it is virtual. When overriding a method, use virtual in order to be more explicit - no other difference :)
扩展 Light Races 的答案,也许这会帮助一些人了解它在做什么。
Extending on Light Races answer, maybe this will help some people to see what it is doing.