在C++11中引入了override关键字,以帮助防止在覆盖虚函数时出现的一些小问题。例如,在下面的程序中就存在这样的错误。
// This program has a subtle error in the virtual functions.
#include <iostream>
#include <memory>
using namespace std;
class Base
{
public:
virtual void functionA(int arg) const{cout << "This is Base::functionA" << endl; }
};
class Derived : public Base
{
public:
virtual void functionA(long arg) const{ cout << "This is Derived::functionA" << endl; }
};
int main()
{
// Base pointer b points to a Derived class object.
shared_ptr<Base>b = make_shared<Derived>();
// Call virtual functionA through Base pointer.
b->functionA(99);
return 0;
}
程序输出结果:
This is Base::functionA
在该程序中,Base类指针b指向Derived类对象。因为function A是一个虚函数,所以一般可以认为b对functionA的调用将选择Derived类的版本。