C++ override关键字

283 阅读1分钟

override

C++ 为什么需要override关键字?

override是C++11引入的关键字

一般程序员在写继承类的函数时,程序员自己是清楚是否override基类的虚函数的但有可能不小心写错了函数签名,这时候如果没有override,程序可以正常编译(直到需要多态时,才会发现无法实现动态调用)

而如果加上了override关键字,编译器在编译时就会去基类中寻找同签名的虚函数,如果没有找到就会编译出错

#include <iostream>

using namespace std;

class Base{
public:
    virtual void play(int x);
};

void Base::play(int x) {
    cout << "base play: " << x << endl;
}

class Derived: public Base {
public:
    void play(double x);
};

void Derived::play(double x) {
    cout << "derived play: " << x << endl;
}

int main() {
    Base* b = new Derived();
    b->play(3);
    return 0;
}
$ g++ -std=c++11 test_override.cc -o test_conversion;./test_conversion                   
base play: 3

如上所示,本意是希望实现多态,但是不小心写错了函数签名,但程序可以正常编译运行,直到运行时才能看到bug

在derived类play方法后面加上override关键字后,程序无法编译,可以很快找到bug

$ g++ -std=c++11 test_override.cc -o test_conversion;./test_conversion                   
test_override.cc:16:25: error: non-virtual member function marked 'override' hides virtual member function
    void play(double x) override;
                        ^
test_override.cc:7:18: note: hidden overloaded virtual function 'Base::play' declared here: type mismatch at 1st parameter ('int' vs 'double')
    virtual void play(int x);
                 ^
1 error generated.
base play: 3

正确程序

#include <iostream>

using namespace std;

class Base{
public:
    virtual void play(int x);
};

void Base::play(int x) {
    cout << "base play: " << x << endl;
}

class Derived: public Base {
public:
    void play(int x) override;
};

void Derived::play(int x) {
    cout << "derived play: " << x << endl;
}

int main() {
    Base* b = new Derived();
    b->play(3);
    return 0;
}
g++ -std=c++11 test_override.cc -o test_conversion;./test_conversion                   eniac@EniacdeMacBook-Air
derived play: 3

结论

总而言之,override一方面是为了阅读程序更方便,另一方面也防止程序员写代码时出现因为粗心而导致的bug