设计一个类animal和它的派生类tiger(虎)、sheep(羊),实现虚函数。
要求:可自行定义这些类的成员变量,但animal基类中应有动物性别的成员变量,但要说明每种动物的叫soar()及吃eat()的成员函数,可用cout输出来表示。
要求每个派生类生成两个对象,打乱次序存于一个数组中,然后用循环程序访问其叫与吃的成员函数,必须用到虚函数。
#include<iostream>
#include<string>
using namespace std;
class animal { //基类animal
public:
animal(){ //构造函数,确定性别
cout << "Please enter the sex of the animal:\n";
cin >> sex;
};
virtual void soar()=0 {}; //两个纯虚函数
virtual void eat()=0 {};
protected:
string sex;
};
class tiger :public animal { //派生类tiger
public:
virtual void soar() {
cout << "Tiger's soar: Ao~~" << endl;
};
virtual void eat() {
cout << "Tiger eats meat!" << endl;
};
};
class sheep :public animal { //派生类sheep
public:
virtual void soar() {
cout << "Sheep's soar: Baa~~" << endl;
};
virtual void eat() {
cout << "Sheep eats grass!" << endl;
};
};
int main() {
tiger t1, t2;
sheep s1, s2;
animal *array[4] = { &s1, &s2, &t1, &t2 }; //定义指针数组
for (int i = 0; i < 4; i++) { //利用循环调用成员函数
array[i]->eat(); //动态关联
array[i]->soar();
}
return 0;
}
运行结果(输入的四个对象性别均为male)⬇