c++定义一个动物(Animal)基类,具有 Age、Weight 等数据成员,Walk、 Breath 等成员函数,其中 Breath 是虚函数。由 Animal 派生出鱼(Fish)类和陆地动 物(TerrestrialAnimal)类。Fish 类有鳍(Fim)数据成员,TerrestrialAnimal 类有腿 (Leg)数据成员。在 Fish 类和 TerrestrialAnimal 类中重载成员函数 Walk 实现静态 多态,Breath 利用 virtual 实现动态多态性,并测试类的多态性
时间: 2024-03-14 08:42:40 浏览: 205
C++之普通成员函数、虚函数以及纯虚函数的区别与用法要点
好的,以下是 C++ 的实现:
```cpp
#include <iostream>
using namespace std;
class Animal {
public:
int age;
double weight;
void Walk() {
cout << "Animal is walking." << endl;
}
virtual void Breath() {
cout << "Animal is breathing." << endl;
}
};
class Fish : public Animal {
public:
int fin;
void Walk() {
cout << "Fish cannot walk." << endl;
}
void Breath() override {
cout << "Fish is breathing underwater." << endl;
}
};
class TerrestrialAnimal : public Animal {
public:
int leg;
void Walk() {
cout << "Terrestrial animal is walking." << endl;
}
void Breath() override {
cout << "Terrestrial animal is breathing air." << endl;
}
};
int main() {
Animal* animal1 = new Animal();
animal1->Walk();
animal1->Breath();
Fish* fish1 = new Fish();
fish1->Walk();
fish1->Breath();
TerrestrialAnimal* ta1 = new TerrestrialAnimal();
ta1->Walk();
ta1->Breath();
Animal* animal2 = new Fish();
animal2->Walk();
animal2->Breath();
Animal* animal3 = new TerrestrialAnimal();
animal3->Walk();
animal3->Breath();
delete animal1;
delete fish1;
delete ta1;
delete animal2;
delete animal3;
return 0;
}
```
输出结果为:
```
Animal is walking.
Animal is breathing.
Fish cannot walk.
Fish is breathing underwater.
Terrestrial animal is walking.
Terrestrial animal is breathing air.
Fish cannot walk.
Fish is breathing underwater.
Terrestrial animal is walking.
Terrestrial animal is breathing air.
```
可以看到,Fish 类和 TerrestrialAnimal 类中的 Walk() 函数虽然重载了 Animal 类中的 Walk() 函数,但是在多态调用时,只会调用 Animal 类中的 Walk() 函数。而 Breath() 函数则利用了 virtual 关键字实现了动态多态性,可以在运行时根据实际类型来调用对应的 Breath() 函数。
阅读全文