运用虚函数实现多态
cpp
#include <iostream>
using namespace std;
class Animal
{
public:
virtual void perform()=0;
virtual ~Animal()
{
cout << "释放父类空间" <<endl;
}
};
class Monkey:public Animal
{
public:
void perform()
{
cout << "猴子正在骑自行车" << endl;
}
~Monkey()
{
cout << "释放子类空间" << endl;
}
};
class Elepant:public Animal
{
public:
void perform()
{
cout << "大象正在滚皮球" << endl;
}
};
class Lion:public Animal
{
public:
void perform()
{
cout << "狮子正在跳火圈" << endl;
}
};
int main()
{
Animal *p;
Monkey s1;
p=&s1;
p->perform();
Lion s2;
p=&s2;
p->perform();
Elepant s3;
p=&s3;
p->perform();
cout << "Hello World!" << endl;
return 0;
}
实现效果