c++基础-动态关联,设计一个类animal和它的派生类tiger(虎)、sheep(羊),实现虚函数

设计一个类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)⬇
在这里插入图片描述

  • 5
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值