使用“替代"或“最终"说明符时,“虚拟"关键字是否不是多余的? [英] Isn't 'virtual' keyword redundant when 'override' or 'final' specifiers are used?

查看:78
本文介绍了使用“替代"或“最终"说明符时,“虚拟"关键字是否不是多余的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下基类:

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关键字,如果没有重写方法,则overridefinal都会给您一个编译器错误,但是您或其他人可能希望将来删除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屋!

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