以下是一个简单的比喻,将多态概念与生活中的实际情况相联系:比喻:动物园的讲解员和动物表演
想象一下你去了一家动物园,看到了许多不同种类的动物,如狮子、大象、猴子等。现在,动物园里有一位讲解员,他会为每种动物表演做简单的介绍。
在这个场景中,我们可以将动物比作是不同的类,而每种动物表演则是类中的函数。而讲解员则是一个基类,他可以根据每种动物的特点和表演,进行相应的介绍。
具体过程如下:
定义一个基类Animal,其中有一个虚函数perform (),用于在子类中实现不同的表演行为。
#include <iostream>using namespace std;
class Animal
{
public:string name;string weight;Animal(){}Animal(string name,string weight):name(name),weight(weight){}virtual void perform() = 0;
};
class Elephant: public Animal
{
private:string height;
public:Elephant(){}Elephant(string name,string weight,string height):Animal(name,weight),height(height){}void perform(){cout << name << weight << height << endl;cout << "它有长长的鼻子和象牙。。。 " << endl;}
};
class Monkey:public Animal
{
private:string color;
public:Monkey(){}Monkey(string name,string weight,string color):Animal(name,weight),color(color){}void perform(){cout << name << weight << color << endl;cout << "它爬上了大树。。。 " << endl;}
};
class Lion:public Animal
{
private:int age;
public:Lion(){}Lion(string name,string weight,int age):Animal(name,weight),age(age){}void perform(){cout << name << weight << age << endl;cout << "它会吼叫,吼。。。 " << endl;}
};
int main()
{Animal *p1;Elephant a ("李白","2吨半","三米高");p1 = &a;p1->perform();Animal *p2;Monkey b ("周杰伦","40斤","黄色");p2 = &b;p2->perform();Animal *p3;Lion c ("热巴","200斤",5);p3 = &c;p3->perform();return 0;
}