繁体   English   中英

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

[英]Override identifier after destructor in C++11

虚拟析构函数声明后的覆盖标识符是否有任何特殊含义?

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
    {}
};

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

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

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

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

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

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

10.3虚函数

6 /尽管析构函数不是继承的,但派生类中的析构函数会覆盖声明为virtual的基类析构函数; 见12.4和12.5。

如果将此与前一条款一起使用:

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 }; 

- 末端的例子]

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM