1、比喻:动物园的讲解员和动物表演
想象一下你去了一家动物园,看到了许多不同种类的动物,如狮子、大象、猴子等。现在,动物园里有一位讲解员,他会为每种动物表演做简单的介绍。
在这个场景中,我们可以将动物比作是不同的类,而每种动物表演则是类中的函数。而讲解员则是一个基类,他可以根据每种动物的特点和表演,进行相应的介绍。
具体过程如下:
定义一个基类Animal,其中有一个虚函数perform 0,用于在子类中实现不同的表演行为
#include <iostream>
using namespace std;
class Speaker
{
private:
string name;
public:
Speaker(){}
Speaker(string name):name(name)
{
cout<<"sqeaker::有参构造函数"<<endl;
}
virtual void perform()=0;
};
class Monkey:public Speaker
{
private:
string name;
string act;
public:
Monkey(){}
Monkey(string name,string act,string n):Speaker(n),name(name),act(act)
{
cout<<"monkey::有参构造函数"<<endl;
}
void perform()
{
cout<<"猴子正在"<<act<<endl;
}
~Monkey(){}
};
class Lion:public Speaker
{
private:
string name;
int age;
string act;
public:
Lion(){}
Lion(string name,int age,string act,string n):Speaker(n),age(age),name(name),act(act)
{
cout<<"Lion::有参构造函数"<<endl;
}
void perform()
{
cout<<"狮子正在"<<act<<endl;
}
~Lion(){}
};
int main()
{
Lion l1("辛巴",3,"走钢丝","lisi");
Speaker *s=&l1;
s->perform();
Monkey m1("齐天大圣","闹天宫","lisi");
s=&m1;
s->perform();
return 0;
}
运行结果:
2、封装一个动物的基类,类中有私有成员:姓名,颜色,指针成员年纪
再封装一个狗这样类,共有继承于动物类,自己拓展的私有成员有:指针成员:腿的个数整型int count),共有成员函数:会叫: void speak()
要求:分别完成基类和派生类中的: 构造函数、析构函数、拷贝构造函数、拷贝赋值函数
#include <iostream>
using namespace std;
//父类
class Animal
{
private:
string name;
string color;
int *age;
public:
//无参构造
Animal()
{
cout<<"Animal父类::无参构造函数"<<endl;
}
//有参构造
Animal(string name,string color,int age):name(name),color(color),age(new int(age))
{
cout<<"Animal父类::有参构造函数"<<endl;
}
//拷贝构造函数
Animal(const Animal &other):name(other.name),color(other.color),age(new int(*other.age))
{
cout<<"Animal父类::拷贝构造函数"<<endl;
}
//析构函数
~Animal()
{
delete age;
cout<<"父类::析构函数"<<endl;
}
//拷贝赋值函数
Animal &operator=(const Animal &other)
{
if(this!=&other)
{
name=other.name;
color=other.color;
age=new int(*other.age);
}
cout<<"父类::拷贝赋值函数"<<endl;
return *this;
}
};
//子类
class Dog:public Animal
{
private:
int *count;
public:
Dog()
{
cout<<"子类::无参构造"<<endl;
}
Dog(string name,string color,int age,int count):Animal(name,color,age),count(new int(count))
{
cout<<"子类::有参构造函数"<<endl;
}
//拷贝构造函数
Dog(const Dog &other):Animal(other),count(other.count)
{
cout<<"子类::拷贝构造函数"<<endl;
}
//拷贝赋值函数
Dog &operator=(const Dog &other)
{
if(this!=&other)
{
Animal::operator=(other);
count=other.count;
}
cout<<"子类::拷贝赋值函数"<<endl;
return *this;
}
~Dog()
{
delete count;
cout<<"子类::析构函数"<<endl;
}
};
int main()
{
Dog d1;
Dog d2("小土狗","黄色",2,4);
Dog d3(d2);
d1=d3;
return 0;
}
运行结果: