C++11 override

作用

在成员函数声明或定义中, override 确保该函数为虚函数并覆写来自基类的虚函数。
位置:函数调用运算符之后,函数体或纯虚函数标识 “= 0” 之前。

不使用override

#include <iostream>
using namespace std;

class Base
{
public:
	virtual void foo() { cout << "Base::foo" << endl; }
	virtual void goo() { cout << "Base::goo" << endl; }
	// ...
};

class Derived : public Base
{
public:
	void foo() { cout << "Derived::foo" << endl; }
	void gao() { cout << "Derived::goo" << endl; } // 错误的将goo写成了gao,但编译器并不会给出提示
	// ...
};

int main(void)
{
	Derived d;
	d.foo();                  // Derived::foo
	d.goo();                  // Base::goo 很明显,这不是我们想要的结果
	
	return 0;
}

使用override

#include <iostream>
using namespace std;

class Base
{
public:
    virtual void foo()
    {
        cout << "Base::foo()" << endl;
    }

    virtual void bar()
    {
        cout << "Base::bar()" << endl;
    }

    void goo()
    {
        cout << "Base::goo()" << endl;
    }
};

class Derived : public Base
{
public:
    void foo() override          // ok
    {
        cout << "Derived::foo()" << endl;
    }

    void foo() const override    // error: Derived::foo does not override. signature mismatch.
    {
        cout << "Derived::foo()" << endl;
    }

    void goo() override          // error: Base::goo is not virtual
    {
        cout << "Derived::goo()" << endl;
    }

    void bao() override          // error: 将bar误写成了bao,且基类中无名为bao的虚函数,
    {                            // 由于使用了override,编译器会检测出此错误
        cout << "Derived::bao()" << endl;
    }
};

在派生类的成员函数中使用override时,如果基类中无此函数,或基类中的函数并不是虚函数,编译器会给出相关错误信息。

猜你喜欢

转载自blog.csdn.net/linuxwuj/article/details/83183381