C++0x 中的最终虚拟函数
读到您可以在 C++0x 中拥有 最终虚拟函数 我是有点困惑。与一开始就省略两个修饰符有什么区别?
Reading that you can have final virtual functions in C++0x I am bit confused. What is the difference to just omitting both modifiers in the first place?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
区别在于不是使用它的基础,而是派生的。
不要将其视为防止覆盖,而是防止“更多”覆盖。
The difference occurs it's not the base that uses it, but the derived.
Think of it not as preventing overrides, but preventing "any more" overrides.
当我第一次在 C++ 中使用
final
关键字和virtual
时,我也想知道同样的事情:我认为这个问题当前接受的答案很好,但我想根据我的情况进一步构建它发现调查这个。
考虑下面的类:
要认识到的重要一点是这三个方法声明都是不同的并且意味着不同的东西。
第一个:
是非虚拟的,因此根据定义,不能被覆盖。
第三个:
被声明为
final
,因此根据定义也不能被覆盖。区别在于,由于
hide_me
是非虚拟的,因此覆盖它不适用,而您可以将cant_override_me
视为符合条件 em> 被覆盖(因为它是虚拟
)但是它也具有覆盖禁用,因为final
修饰符。换句话说,重写不适用于未声明为 virtual 的方法,但它确实适用于 virtual 方法,只是如果它们也是 virtual 方法,则无法重写它们声明最终
。现在考虑一个子类:
您可以为类
B
重新定义hide_me()
,但这只是重载或隐藏,因此是函数名称。B
仍然可以通过A::hide_me()
访问A
的hide_me
方法,但其他人已经对声明为B
的B
的引用,即:必须通过以下方式访问
A
现在隐藏的hide_me
定义my_b->A::hide_me()
。您不能在
B
中提供cant_override_me()
的重新定义。作为一个完整的示例,这里对程序进行了轻微的重新定义,以帮助举例说明发生的情况:
程序输出
When I first came across the use of the
final
keyword in conjunction withvirtual
in C++, I was wondering the same thing:I think the current accepted answer to this question is good, but I wanted to build upon it a bit more based on what I found looking into this.
Consider the following class:
The important thing to realize is that the three method declarations are all distinct and mean different things.
The first:
is non-virtual and thus, by definition, cannot be overridden.
The third:
is declared
final
, and thus cannot be overridden, also by definition.The difference is that since
hide_me
is non-virtual, overriding it is unapplicable, whereas you can think ofcant_override_me
as eligible to be overridden (because it isvirtual
,) but it also has overriding disabled due to thefinal
modifier. In other words, overriding doesn't apply to methods that are not declaredvirtual
, but it does apply tovirtual
methods, you just can't override them if they are also declaredfinal
.Now consider a child class:
You can redefine
hide_me()
for classB
, but this is just overloading or hiding, hence the function name.B
can still accessA
'shide_me
method viaA::hide_me()
, but someone else who has a reference toB
declared asB
, i.e.:must access
A
's now-hidden definition ofhide_me
viamy_b->A::hide_me()
.You cannot provide a redefinition of
cant_override_me()
inB
.As a full example, here is a slight redefinition of the program to help exemplify what's going on:
The program outputs