以下是一个简单的比喻,将多态概念与生活中的实际情况相联系:
比喻:动物园的讲解员和动物表演
想象一下你去了一家动物园,看到了许多不同种类的动物,如狮子、大象、猴子等。现在,动物园里有一位进解员,他会为每种动
物表演做简单的介绍。
在这个场景中,我们可以将动物比作是不同的类,而每种动物表演则是类中的函数。而讲解员则是一个基类,他可以根据每种动物
的特点和表演,进行相应的介绍。
具体过程如下:
定义一个基类Animal,其中有一个虚函数perform (,用于在子类中实现不同的表演行为。
#include <iostream>using namespace std;
class Zoo
{
public:Zoo(){cout << "Zoo::无参构造" << endl;}virtual ~Zoo(){cout << "Zoo::虚析构" << endl;}virtual void show()=0;
};
class Monkey:public Zoo
{
private:string name;string sex;int age;
public:Monkey() {cout << "Monkey::无参构造" << endl;}Monkey(string name,string sex,int age):name(name),sex(sex),age(age){cout << "Monket::有参构造" << endl;}~Monkey(){cout << "Monkety::析构" << endl;}void show(){cout << name << endl;cout << sex << endl;cout << age << endl;cout << "这只猴子正在吃香蕉" << endl;}
};
class Panda:public Zoo
{
private:string name;string sex;int age;
public:Panda() {cout << "Panda::无参构造" << endl;}Panda(string name,string sex,int age):name(name),sex(sex),age(age){cout << "Monket::有参构造" << endl;}~Panda(){cout << "Panda::析构" << endl;}void show(){cout << name << endl;cout << sex << endl;cout << age << endl;cout << "这只熊猫正在吃竹子" << endl;}
};
int main()
{Zoo *z;Monkey m("吉吉国王","雄性",12);z=&m;z->show();Panda p("阿宝","雄性",12);z=&p;z->show();return 0;
}
封装
个动物的基类
类中有私有成员:姓名,颜色,指针成员年纪
再封装一个狗这样类,共有继承于动物类,自己拓展的私有成员有:指针成员:腿的个数(整型 int count),共有成员函数:会
叫: void speak()
要求:分别完成基类和派生类中的:构造函数、析构函数、拷贝构造函数、拷贝赋值函数
eg
Dog d1;
Dog d2(....);
Dog d3(d2);
d1 = d3
#include <iostream>using namespace std;
class Zoo
{
private:string name;string color;int *age;
public:Zoo(){cout << "Zoo::无参构造" << endl;}Zoo(string name,string color,int age):name(name),color(color),age(new int(age)){cout << "Zoo::有参构造" << endl;}Zoo(const Zoo &other):name(other.name),color(other.color),age(new int(*other.age)){cout << "Zoo::拷贝构造" << endl;}Zoo & operator=(const Zoo &other){cout << "Zoo::拷贝赋值" << endl;if(this != &other){name=other.name;color=other.color;age=new int(*other.age);}return *this;}~Zoo(){cout << "Zoo::析构" << endl;delete age;}
};
class Dog:public Zoo
{
private:int *foot;
public:Dog(){cout << "Dog::无参构造" << endl;}Dog(int foot,string name,string color,int age):Zoo(name,color,age),foot(new int(foot)){cout << "Dog::有参构造" << endl;}Dog(const Dog &other):Zoo(other),foot(new int(*other.foot)){cout << "Dog::拷贝构造" << endl;}Dog & operator=(const Dog &other){if(this != &other){Zoo::operator=(other);foot=new int(*other.foot);}return *this;}~Dog(){cout << "Dog::析构" << endl;delete foot;}void speak(){cout << "汪汪汪汪汪汪汪" << endl;}};
int main()
{Dog d1;Dog d2(4,"旺财","黄",5);Dog d3(d2);d1=d3;d2.speak();return 0;
}