是否有反对'覆盖' C ++中的说明符?

时间:2017-01-25 15:32:10

标签: c++ c++11 inheritance override

override关键字允许确保该函数将被覆盖。 我正在寻找相反的功能。所以 - 当我写一个新函数时 - 我想用它来标记它以确保它不会被意外覆盖。

(另外,我不想让它static,因为它看起来像属于一个对象而不是类)

3 个答案:

答案 0 :(得分:7)

  

我想用一些东西来标记,以确保它不会被意外覆盖。

您可以使用final specifier cppreference 的示例:

struct Base
{
    virtual void foo();
};

struct A : Base
{
    void foo() final; // A::foo is overridden and it is the final override
    void bar() final; // Error: non-virtual function cannot be overridden or be final
};

答案 1 :(得分:5)

如果您不希望在派生类中覆盖虚拟函数,可以使用final

  

指定无法在派生类中重写虚函数,或者无法继承类。

e.g。

struct Base
{
    virtual void foo() final; // foo cannot be overridden in the derived class
};
struct Derived : Base
{
    void foo();               // Error: foo cannot be overridden as it's final in Base
};

答案 2 :(得分:0)

final是您要查找的关键字。

备注:请注意override没有"确保该功能将被覆盖"就像你说的那样。 派生类中的override确实会确保您实际覆盖基类的方法,而不仅仅是引入一个类似于基类的虚方法的新方法。 / p>

为了确保方法被覆盖,它必须在基类中是纯虚拟的。

此外,static完全相反:静态方法属于类,非静态方法需要调用对象。