What#39;s the point of a final virtual function?(最终的虚函数有什么意义?)
问题描述
维基百科有以下关于 C++11 final 修饰符的例子:
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
};
我不明白引入虚函数并立即将其标记为最终函数的意义.这只是一个不好的例子,还是有更多的例子?
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.
这篇关于最终的虚函数有什么意义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:最终的虚函数有什么意义?
基础教程推荐
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- CString 到 char* 2021-01-01
