2.试编程:
封装一个动物的基类,类中有私有成员:姓名,颜色,指针成员年纪
再封装一个狗这样类,共有继承于动物类,自己拓展的私有成员有:指针成员:腿的个数(整型 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* y;
public:zoo(){}zoo(string name,string color, int y):name(name),color(color),y(new int(y)){cout << "父类:有参构造函数" << endl;}~zoo(){delete y;cout << "父类:析构函数" << endl;}zoo(const zoo &other):name(other.name),color(other.color),y(other.y){cout << "父类:拷贝构造函数" << endl;}zoo &operator=(const zoo &other){if( this !=&other){name=other.name;color=other.color;y=new int(*other.y);}cout << "父类:拷贝赋值函数" << endl;return *this;}void show(){cout << name << endl;cout << color << endl;cout << *y << endl;}
};
class dog:public zoo
{
private:int * leg;
public:dog(){}dog( int leg,string name,string color,int y):zoo(name,color,y),leg(new int(leg)){cout << "子类:有参构造函数" << endl;}~dog(){delete leg;cout << "子类:析构函数" << endl;}dog(const dog &other):zoo(other),leg(other.leg){cout << "子类:拷贝构造函数" << endl;}dog &operator=(const dog &other){if(this != &other){zoo::operator=(other);leg=other.leg;}cout << "子类:拷贝赋值函数" << endl;return *this;}void show(){cout << *leg << endl;zoo::show();}};int main()
{dog s(4,"zwt","yellow",3);dog s1;s1=s;dog s2(s1);s.show();s1.show();s2.show();return 0;
}
3.编程题:
以下是一个简单的比喻,将多态概念与生活中的实际情况相联系:
比喻:动物园的讲解员和动物表演
想象一下你去了一家动物园,看到了许多不同种类的动物,如狮子、大象、猴子等。现在,动物园里有一位讲解员,他会为每种动物表演做简单的介绍。
在这个场景中,我们可以将动物比作是不同的类,而每种动物表演则是类中的函数。而讲解员则是一个基类,他可以根据每种动物的特点和表演,进行相应的介绍。
具体过程如下:
定义一个基类 Animal,其中有一个虛函数perform(),用于在子类中实现不同的表演行为
#include <iostream>using namespace std;class human
{
private:string name;
public:human() {}human(string name):name(name){cout << "我是讲解员:" << name << endl;}virtual void speak() = 0;virtual ~human(){cout << "稍等" << endl;}
};
class elephant:public human
{
private:string name;
public:elephant() {}elephant(string n,string name):human(n),name(name){}void speak(){cout << "这是我们园内最出名的熊猫,叫" << name << ",他最喜欢吃嫩笋" << endl;}
};
class monkey:public human
{
private:string name;
public:monkey (){}monkey(string n,string name):human(n),name(name){}void speak(){cout << "接下来让我们看看大明星——长颈鹿,名为:" << name << ",他十分喜欢散步" << endl;}};
int main()
{elephant e1("meldy","圆圆");human *p = &e1;p->speak();monkey m1("meldy","欢欢");p = &m1;p->speak();
}