用C++设计一个基类Animal 和它的派生类Tiger(老虎)、Sheep(羊),实现虚函数。提示:可自行定义这些类的成员变量,但Animal基类中应有动物性别的成员变量,但要说明每种动物的叫soar()及吃eat()的成员函数,可用cout输出来表示。要求每个派生类生成两个对象,打乱次序存于一个数组中,然后用循环程序访问其soar()与eat()的成员函数,必须用到虚函数。
时间: 2024-02-11 18:10:05 浏览: 21
好的,我来为您提供完整的代码:
```c++
#include <iostream>
#include <cstdlib>
#include <ctime>
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;
}
};
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]);
}
}
for (int i = 0; i < 4; i++) {
animals[i]->soar();
animals[i]->eat();
cout << endl;
}
return 0;
}
```
这个程序会生成4个Animal类的派生类对象,包括2个Tiger对象和2个Sheep对象,然后打乱存储顺序,最后访问每个对象的soar()和eat()虚函数。每个对象的性别由一个字符表示,这个字符在生成对象的时候被传递给构造函数。