c++11 关键字 override 使用

写在最前。。。

请支持原创~~ 

1. 功能

用在类中成员函数声明的地方,用以标记一个virtual function 是重写另一个 virtual function;

2. 语法

  • 只声明时,override 紧跟参数的右括号,如果是纯虚函数,override 会出现在 = 0 之前;
  • 类中定义时,override 在 函数体之前;

3. 举例

#include <iostream>
 
struct A
{
    virtual void foo();
    void bar();
    virtual ~A();
};
 
// member functions definitions of struct A:
void A::foo() { std::cout << "A::foo();\n"; }
A::~A() { std::cout << "A::~A();\n"; }
 
struct B : A
{
//  void foo() const override; // Error: B::foo does not override A::foo
                               // (signature mismatch)
    void foo() override; // OK: B::foo overrides A::foo
//  void bar() override; // Error: A::bar is not virtual
    ~B() override; // OK: `override` can also be applied to virtual
                   // special member functions, e.g. destructors
    void override(); // OK, member function name, not a reserved keyword
};
 
// member functions definitions of struct B:
void B::foo() { std::cout << "B::foo();\n"; }
B::~B() { std::cout << "B::~B();\n"; }
void B::override() { std::cout << "B::override();\n"; }
 
int main()
{
    B b;
    b.foo();
    b.override(); // OK, invokes the member function `override()`
    int override{42}; // OK, defines an integer variable
    std::cout << "override: " << override << '\n';
}

重写的函数加上override,那么该成员函数需要满足:

  • 成员函数为 虚函数;
  • 成员函数从父类继承,在子类重写;

另外,如同 关键字 final, 只是一个标识,在使用成员函数时有特殊的意义。而在其他情况下可以作为一个对象名、函数名、类名使用。

扫描二维码关注公众号,回复: 14974018 查看本文章

结果:

B::foo();
B::override();
override: 42
B::~B();
A::~A();

4. 原文摘录 

Specifies that a virtual function overrides another virtual function.
The identifier override, if used, appears immediately after the declarator in the syntax of a member function declaration or a member function definition inside a class definition.


1) In a member function declaration, override may appear in virt-specifier-seq immediately after the declarator, and before the pure-specifier, if used.
2) In a member function definition inside a class definition, override may appear in virt-specifier-seq immediately after the declarator and just before function-body.
In both cases, virt-specifier-seq, if used, is either override or final, or final override or override final.


In a member function declaration or definition, override specifier ensures that the function is virtual and is overriding a virtual function from a base class. The program is ill-formed (a compile-time error is generated) if this is not true.


override is an identifier with a special meaning when used after member function declarators: it's not a reserved keyword otherwise.

猜你喜欢

转载自blog.csdn.net/jingerppp/article/details/129275701