定义一个包含纯虚函数的基类Animal,定义具体的动物如: 狮子、熊猫、猫、狗继承自Animal类
Animal类中包含纯虚函数sound(),perform(), 在子类中,对纯虚函数进行重写;要求: 定义一个全局函数,形参固定,通过不同的实参完成在全局函数中对不同类重写的perform和sound的调用
#include <iostream>
using namespace std;
class Animal
{
public:
virtual void sound()=0;
virtual void perform()=0;
};
class Lion:public Animal
{
void sound();
void perform();
};
void Lion::sound()
{
cout<<"狮子叫"<<endl;
}
void Lion::perform()
{
cout<<"狮子捕猎"<<endl;
}
class Panda:public Animal
{
void sound();
void perform();
};
void Panda::sound()
{
cout<<"熊猫叫"<<endl;
}
void Panda::perform()
{
cout<<"熊猫吃竹子"<<endl;
}
class Cat:public Animal
{
void sound();
void perform();
};
void Cat::sound()
{
cout<<"小猫叫"<<endl;
}
void Cat::perform()
{
cout<<"猫抓老鼠"<<endl;
}
class Dog:public Animal
{
void sound();
void perform();
};
void Dog::sound()
{
cout<<"小狗叫"<<endl;
}
void Dog::perform()
{
cout<<"小狗看家"<<endl;
}
//全局函数
void show(Animal &p)
{
p.sound();
p.perform();
}
int main()
{
Cat c1;
show(c1);
Dog d1;
show(d1);
Lion l1;
show(l1);
Panda p1;
show(p1);
//cout << "Hello World!" << endl;
return 0;
}