- 重载:指在同一作用域内,有多个同名但参数不同的函数的现象,叫重载;可以是任何用户定义的函数,例如 类成员函数、类静态函数、普通函数
- 重写:子类重写父类的同名函数,只要子类出现有父类的同名函数,父类中所有该名称的函数都被重写,子类中无法再访问父类中定义该名称的函数,不管子类函数的参数类型是什么。除了覆盖的情况。
- 覆盖:指子类实现了父类中的同名virtual函数,且函数参数与返回值完全一致。
#include <iostream>
#include <string>
using namespace std;
class Animal
{
public:
void run()
{
cout << "Animal run " << endl;
}
void run(int speed)
{
cout << "Animal run " << speed << "m/s" << endl;
}
virtual void eat(string food)
{
cout << "Animal eat " << food << endl;
}
};
class Rabbit : public Animal
{
public:
void run(int speed)
{
cout << "Rabbit run " << speed << "m/s" << endl;
}
void eat(string food) override
{
cout << "Rabbit eat " << food << endl;
}
void eat()
{
cout << "Rabbit eat nothing" << endl;
}
};
int main()
{
Animal *animal = new Rabbit;
animal->run();
animal->run(100);
animal->eat("apple");
Rabbit *rabbit = (Rabbit *)animal;
rabbit->run(100);
rabbit->eat("apple");
rabbit->eat();
return 0;
}