最终虚拟函数的要点是什么? [英] What's the point of a final virtual function?

查看:131
本文介绍了最终虚拟函数的要点是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

维基百科在C ++ 11最后修改器上有以下示例:

Wikipedia has the following example on the C++11 final modifier:

struct Base2 {
    virtual void f() final;
};

struct Derived2 : Base2 {
    void f(); // ill-formed because the virtual function Base2::f has been marked final
};

我不明白引入虚拟函数并立即将其标记为final的意义。

I don't understand the point of introducing a virtual function and immediately marking it as final. Is this simply a bad example, or is there more to it?

推荐答案

通常 final 不会用于虚函数的基类定义。 final 将被覆盖该函数的派生类使用,以防止进一步导出的类型进一步覆盖该函数。由于覆盖函数必须是正常的,这意味着任何人都可以在另一个派生类型中覆盖该函数。 final 允许指定一个覆盖另一个但不能被自己覆盖的函数。

Typically final will not be used on the base class' definition of a virtual function. final will be used by a derived class that overrides the function in order to prevent further derived types from further overriding the function. Since the overriding function must be virtual normally it would mean that anyone could override that function in a further derived type. final allows one to specify a function which overrides another but which cannot be overridden itself.

重新设计类层次结构并需要重写一个函数,但是你不想允许类层次结构的用户做同样的事情,那么你可以在派生类中将这些函数标记为final。

For example if you're designing a class hierarchy and need to override a function, but you do not want to allow users of the class hierarchy to do the same, then your might mark the functions as final in your derived classes.

这篇关于最终虚拟函数的要点是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆