C++定义一个动物( Animal )基类,具有 Age 、 Weight 等数据成员, Walk 、 Breath 等成员函数,其中 Breath 是虚函数。由 Animal 派生出鱼( Fish )类和陆地动物( TerrestrialAnimal )类。 Fish 类有鳍( Fim )数据成员, TerrestrialAnimal 类有腿( Leg )数据成员。在 Fish 类和 TerrestrialAnimal 类中重载成员函数 Walk 实现静态多态, Breath 利用 virtual 实现动态多态性,并测试类的多态性
时间: 2024-03-14 21:44:49 浏览: 92
好的,以下是C++的代码实现:
```c++
#include<iostream>
using namespace std;
class Animal{
protected:
int age;
float weight;
public:
Animal(){}
Animal(int a, float w):age(a), weight(w){}
virtual void Breath(){
cout<<"Animal breathes."<<endl;
}
void Walk(){
cout<<"Animal walks."<<endl;
}
};
class Fish: public Animal{
private:
int fin;
public:
Fish(){}
Fish(int a, float w, int f):Animal(a, w), fin(f){}
void Breath() override{
cout<<"Fish breathes by gills."<<endl;
}
void Walk(){
cout<<"Fish can't walk."<<endl;
}
};
class TerrestrialAnimal: public Animal{
private:
int leg;
public:
TerrestrialAnimal(){}
TerrestrialAnimal(int a, float w, int l):Animal(a, w), leg(l){}
void Breath() override{
cout<<"Terrestrial animal breathes by lungs."<<endl;
}
void Walk(){
cout<<"Terrestrial animal walks on "<<leg<<" legs."<<endl;
}
};
int main(){
Animal* p;
Fish f(1, 0.1, 2);
TerrestrialAnimal t(2, 10, 4);
p=&f;
p->Breath();
p->Walk();
p=&t;
p->Breath();
p->Walk();
return 0;
}
```
输出结果为:
```
Fish breathes by gills.
Fish can't walk.
Terrestrial animal breathes by lungs.
Terrestrial animal walks on 4 legs.
```
可以看到,通过虚函数实现了动态多态性,Fish 和 TerrestrialAnimal 都重写了 Breath 函数,输出结果不同。而通过在 Fish 和 TerrestrialAnimal 中重载 Walk 函数实现了静态多态性,输出结果也不同。这就是类的多态性。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://img-home.csdnimg.cn/images/20250102104920.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)