在C++中,可以使用override关键字来显式地指示函数重写基类的虚函数。override关键字的使用方法如下:
class Base {
public:
virtual void foo() const {
cout << "Base::foo()" << endl;
}
};
class Derived : public Base {
public:
void foo() const override {
cout << "Derived::foo()" << endl;
}
};
int main() {
Derived d;
d.foo(); // 调用Derived类中的foo()函数
return 0;
}
在上述示例代码中,Derived类继承自Base类,并重写了Base类的虚函数foo()。使用override关键字来修饰Derived类中的foo()函数,可以让编译器验证该函数是否真正重写了基类的虚函数。
在main()函数中,我们创建了一个Derived类的对象d并调用了它的foo()函数。由于foo()函数被标记为override,因此编译器会自动调用Derived类中的foo()函数,输出结果为"Derived::foo()"。