在 C++11 中的析构函数之后覆盖标识符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17923370/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 21:33:31  来源:igfitidea点击:

Override identifier after destructor in C++11

c++c++11overridingvirtual-destructor

提问by EnterTheNameHere Bohemian

Does the override identifier after virtual destructor declaration have any special meaning?

虚析构函数声明后的覆盖标识符有什么特殊含义吗?

class Base
{
public:
    virtual ~Base()
    {}

    virtual int Method() const
    {}
};

class Derived : public Base
{
public:
    virtual ~Derived() override
    {}

    virtual int Method() override // error: marked override, but does not override - missing const
    {}
};

Using override identifier on virtual method is useful as check: compiler will report error when the Base virtual method is actualy not overriden.

在虚拟方法上使用覆盖标识符作为检查很有用:当 Base 虚拟方法实际上没有被覆盖时,编译器将报告错误。

Does override on virtual destructor has any meaning/function too?

覆盖虚拟析构函数是否也有任何意义/功能?

采纳答案by John Dibling

It is not overridethat has special meaning, but the destructor itself:

不是override它有特殊意义,而是析构函数本身:

10.3 Virtual Functions

10.3 虚拟功能

6/Even though destructors are not inherited, a destructor in a derived class overrides a base class destructor declared virtual; see 12.4 and 12.5.

6/即使析构函数没有被继承,派生类中的析构函数会覆盖声明为虚拟的基类析构函数;见 12.4 和 12.5。

If you take this in conjunction with the previous clause:

如果您将其与上一条一起考虑:

5/If a virtual function is marked with the virt-specifier override and does not override a member function of a base class, the program is ill-formed. [ Example:

struct B { 
    virtual void f(int); 
}; 

struct D : B
{ 
    void f(long) override; // error: wrong signature overriding B::f
    void f(int) override; // OK 
}; 

—end example ]

5/如果一个虚函数被标记为virt-specifier override,并且没有重写基类的成员函数,那么程序就是格式错误的。[ 例子:

struct B { 
    virtual void f(int); 
}; 

struct D : B
{ 
    void f(long) override; // error: wrong signature overriding B::f
    void f(int) override; // OK 
}; 

—结束示例]

you can see that if a destructor is marked overridebut the base class does not have a virtualdestructor, the program is ill-formed.

您可以看到,如果标记了析构函数override但基类没有virtual析构函数,则程序格式错误。

回答by Mankarse

Yes. If the base destructor is not virtual then the overridemarking will cause the program to not compile:

是的。如果基础析构函数不是虚拟的,那么override标记将导致程序无法编译:

class Base
{
public:
    ~Base()
    {}
};

class Derived : public Base
{
public:
    virtual ~Derived() override //error: '~Derived' marked 'override' but does
                                //        not override any member functions
    {}
};