使用“替代"或“最终"说明符时,“虚拟"关键字是否不是多余的? [英] Isn't 'virtual' keyword redundant when 'override' or 'final' specifiers are used?
问题描述
假设我有以下基类:
class Base {
public:
virtual void f() {};
};
如果我想编写一个将覆盖f()
并且不允许将其覆盖到其派生类的类,则可以使用以下方法来编写它:
If I want to write a class that will override the f()
and will not allow to override it to it's derived classes can write it using following approaches:
方法1:
class Derived : public Base {
public:
virtual void f() override final {};
};
方法2:
class Derived : public Base {
public:
void f() final {};
};
当Approach 2
更紧凑并且final
仍然说f()
实际上是虚拟的并且覆盖基类方法时,
Approach 1
将会详细介绍.
Approach 1
is a fully detailed when Approach 2
more compact and final
still says that f()
is actually virtual and overrides the base class method.
哪种方法更合适?
推荐答案
class Derived : public Base {
public:
void f() override final {};
};
也许是那样吗?派生类中不需要virtual
关键字,如果没有重写方法,则override
和final
都会给您一个编译器错误,但是您或其他人可能希望将来删除final
关键字,然后再删除
Maybe that way? virtual
keyword is not needed in derived class, override
and final
both give you a compiler error if there is no method to override, but you or someone else may want to remove final
keyword in future then override
give you a pure intention of your method behavior.
这篇关于使用“替代"或“最终"说明符时,“虚拟"关键字是否不是多余的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!