用c++设计一个基类Animal 和它的派生类Tiger(老虎)、Sheep(羊),实现虚函数。提示:可自行定义这些类的成员变量,但Animal基类中应有动物性别的成员变量,但要说明每种动物的叫soar()及吃eat()的成员函数,可用cout输出来表示。要求每个派生类生成两个对象,打乱次序存于一个数组中,然后用循环程序访问其soar()与eat()的成员函数,必须用到虚函数。
时间: 2024-02-11 20:10:01 浏览: 35
好的,我来为您解答。
下面是Animal类和它的派生类Tiger和Sheep的定义,实现了虚函数:
```c++
#include <iostream>
using namespace std;
class Animal {
public:
char gender; // 动物性别
virtual void soar() {
cout << "动物可以飞,但是每种动物飞的方式不同。" << endl;
}
virtual void eat() {
cout << "动物可以吃东西,但是每种动物吃的东西不同。" << endl;
}
};
class Tiger : public Animal {
public:
Tiger(char g) {
gender = g;
}
void soar() {
cout << "老虎不会飞,只会奔跑。" << endl;
}
void eat() {
cout << "老虎是肉食动物,喜欢吃肉。" << endl;
}
};
class Sheep : public Animal {
public:
Sheep(char g) {
gender = g;
}
void soar() {
cout << "羊也不会飞,只会跑和跳。" << endl;
}
void eat() {
cout << "羊是草食动物,喜欢吃草。" << endl;
}
};
```
下面是生成派生类对象并打乱存储的代码:
```c++
#include <cstdlib> // 包含rand()函数
#include <ctime> // 包含time()函数
int main() {
Animal *animals[4];
char genders[] = {'M', 'F', 'F', 'M'};
srand(time(NULL)); // 设置随机数种子
for (int i = 0; i < 4; i++) {
if (rand() % 2 == 0) {
animals[i] = new Tiger(genders[i]);
} else {
animals[i] = new Sheep(genders[i]);
}
}
```
最后是访问虚函数的代码:
```c++
for (int i = 0; i < 4; i++) {
animals[i]->soar();
animals[i]->eat();
cout << endl;
}
return 0;
}
```
完整代码如下:
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)