1.思维导图
2.
编程题:
以下是一个简单的比喻,将多态概念与生活中的实际情况相联系:
比喻:动物园的讲解员和动物表演
想象一下你去了一家动物园,看到了许多不同种类的动物,如狮子、大象、猴子等。现在,动物园里有一位讲解员,他会为每种动物表演做简单的介绍。
在这个场景中,我们可以将动物比作是不同的类,而每种动物表演则是类中的函数。而讲解员则是一个基类,他可以根据每种动物的特点和表演,进行相应的介绍。
具体过程如下:
定义一个基类 Animal,其中有一个虛函数perform(),用于在子类中实现不同的表演行为。
#include <iostream>
using namespace std;
class Animal
{
private:
string name;
public:
Animal(){}
Animal(string name):name(name)
{
cout << "昵称:" << name << endl;
}
virtual void perform() = 0;
virtual ~Animal()
{
cout << "Animal::析构函数" << endl;
}
};
class Bear:virtual public Animal
{
private:
string per;
int age;
public:
Bear(){}
Bear(string name,int age,string per):Animal(name),per(per),age(age)
{}
~Bear()
{
cout << "Bear::析构函数" << endl;
}
void perform()
{
cout << "年龄:" << age << endl;
cout << "表演:" << per << endl;
}
};
class Monkey:virtual public Animal
{
private:
string per;
int age;
public:
Monkey(){}
Monkey(string name,int age,string per):Animal(name),per(per),age(age)
{}
~Monkey()
{
cout << "Monkey::析构函数" << endl;
}
void perform()
{
cout << "年龄:" << age << endl;
cout << "表演:" << per << endl;
}
};
class Tiger:virtual public Animal
{
private:
string per;
int age;
public:
Tiger(){}
Tiger(string name,int age,string per):Animal(name),per(per),age(age)
{}
~Tiger()
{
cout << "Tiger::析构函数" << endl;
}
void perform()
{
cout << "年龄:" << age << endl;
cout << "表演:" << per << endl;
}
};
int main()
{
Animal *a =new Bear("熊大",5,"上树采蜂蜜");
a->perform();
delete a;
cout << "—————————————————————————" << endl;
Animal *a1 =new Monkey("毛毛",3,"水中捞月");
a1->perform();
delete a1;
cout << "—————————————————————————" << endl;
Animal *a2 =new Tiger("泰哥",6,"撒娇卖萌");
a2->perform();
delete a2;
return 0;
}