在c++中,如果派生类定义了与其基类中定义的函数相同,则称函数重写。 它用于实现运行时多态性。 它使您能够提供已由其基类提供的函数有所区别的特定实现。
c++函数重写/覆盖示例
下面来看看一个简单的c++中函数重写/覆盖的例子。 在这个例子中,我们重写/覆盖了eat()
函数。
#include <iostream>
using namespace std;
class animal {
public:
void eat(){
cout<<"eating...";
}
};
class dog: public animal
{
public:
void eat()
{
cout<<"eating bread...";
}
};
int main(void) {
dog d = dog();
d.eat();
return 0;
}
运行上面代码,得到以下结果 -
eating bread...