位置:首页 > 高级语言 > C++教程 > C++函数重写

C++函数重写

在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...