一、思维导图
二、编程题
以下是一个简单的比喻,将多态概念与生活中的实际情况相联系:
比喻:动物园的讲解员和动物表演
想象一下你去了一家动物园,看到了许多不同种类的动物,如狮子、大象、猴子等。现在,动物园里有一位讲解员,他会为每种动物表演做简单的介绍。
在这个场景中,我们可以将动物比作是不同的类,而每种动物表演则是类中的函数。而讲解员则是一个基类,他可以根据每种动物的特点和表演,进行相应的介绍。
具体过程如下:
定义一个基类 Animal,其中有一个虛函数perform(),用于在子类中实现不同的表演行为。
#include <iostream>
using namespace std;
//父类:讲解员
class Trainer
{
private:
string animal;
public:
Trainer() {}
Trainer(string animal):animal(animal)
{}
virtual void perform() = 0; //纯虚函数
};
//子类:狮子
class Lion:public Trainer
{
private:
int age;
string sex;
public:
Lion() {}
Lion(string animal, int age, string sex):Trainer(animal), age(age), sex(sex)
{}
void perform()
{
cout << "这头" << sex << "已经" << age << "岁了,它正在喷火!" << endl;
}
};
//子类:熊猫
class Panda:public Trainer
{
private:
int age;
string sex;
public:
Panda() {}
Panda(string animal, int age, string sex):Trainer(animal), age(age), sex(sex)
{}
void perform()
{
cout << "这头" << sex << "已经" << age << "岁了,它正在打太极!" << endl;
}
};
//子类:鸡
class Cock:public Trainer
{
private:
int age;
string sex;
public:
Cock() {}
Cock(string animal, int age, string sex):Trainer(animal), age(age), sex(sex)
{}
void perform()
{
cout << "这只" << sex << "已经" << age << "岁了,它正在打篮球!" << endl;
}
};
int main()
{
Trainer *t = nullptr;
Lion l("狮子", 5, "母");
t = &l;
t->perform();
Panda p("熊猫", 4, "公");
t = &p;
t->perform();
Cock c("鸡", 2, "公");
t = &c;
t->perform();
return 0;
}