1.封装一个动物的基类,类中有私有成员:姓名,颜色,指针成员年纪
再封装一个狗这样类,共有继承于动物类,自己拓展的私有成员有:指针成员:腿的个数(整型 int count),共有成员函数:会叫:void speak()
要求:分别完成基类和派生类中的:构造函数、析构函数、拷贝构造函数、拷贝赋值函数
eg : Dog d1;
Dog d2(.....);
Dog d3(d2);
d1 = d3;
代码:
#include <iostream>
using namespace std;
class Zoon
{
private:
string name;
string colour;
int *age;
public:
Zoon()
{
cout << "我是Zoon::无参构造函数" << endl;
}
Zoon(string name,string colour,int age):name(name),colour(colour),age(new int(age))
{
cout << "我是Zoon::有参构造函数" << endl;
}
Zoon(const Zoon &other):name(other.name),colour(other.colour),age(new int(*other.age))
{
cout << "我是Zoon::拷贝构造函数" << endl;
}
Zoon &operator=(const Zoon &other)
{
if(this != &other)
{
name = other.name;
colour = other.colour;
age = new int(*other.age);
}
cout << "我是Zoon::拷贝赋值函数" << endl;
return *this;
}
~Zoon()
{
delete age;
age = nullptr;
cout << "我是Zoon::析构函数" << endl;
}
};
class Dog:public Zoon
{
private:
int *leg;
public:
Dog()
{
cout << "我是Dog::无参构造函数" << endl;
}
Dog(string name,string colour,int age,int leg):Zoon(name,colour,age),leg(new int(leg))
{
cout << "我是Dog::有参构造函数" << endl;
}
Dog(const Dog &other):Zoon(other),leg(new int(*other.leg))
{
cout << "我是Dog::拷贝构造函数" << endl;
}
Dog &operator=(const Dog &other)
{
if(this != &other)
{
Zoon::operator=(other);
leg = new int(*other.leg);
}
cout << "我是Dog::拷贝赋值函数" << endl;
return *this;
}
~Dog()
{
delete leg;
leg = nullptr;
cout << "我是Dog::析构函数" << endl;
}
void speak()
{
cout << "汪汪汪" << endl;
}
};
int main()
{
Dog d1;
Dog d2("方胜","黄",22,4);
Dog d3(d2);
d1 = d3;
return 0;
}
效果图:
2.
以下是一个简单的比喻,将多态概念与生活中的实际情况相联系:
比喻:动物园的讲解员和动物表演
想象一下你去了一家动物园,看到了许多不同种类的动物,如狮子、大象、猴子等。现在,动物园里有一位讲解员,他会为每种动物表演做简单的介绍。
在这个场景中,我们可以将动物比作是不同的类,而每种动物表演则是类中的函数。而讲解员则是一个基类,他可以根据每种动物的特点和表演,进行相应的介绍。
具体过程如下:
定义一个基类 Animal,其中有一个虛函数perform(),用于在子类中实现不同的表演行为。
代码:
#include <iostream>
using namespace std;
class Animal
{
public:
string name;
public:
Animal() {}
Animal(string name):name(name)
{}
virtual ~Animal()
{}
virtual void fun()
{}
};
class A:public Animal
{
public:
A(){}
A(string name):Animal(name)
{}
void fun()
{
cout << "name=" << name << ' ' << "表演:" << "喵喵" << endl;
}
};
class B:public Animal
{
public:
B(){}
B(string name):Animal(name)
{}
void fun()
{
cout << "name=" << name << ' ' << "表演:" << "嗷呜" << endl;
}
};
int main()
{
A a("猫");
B b("狼");
Animal *a1 = &a;
Animal *a2 = &b;
a1->fun();
a2->fun();
return 0;
}
效果图:
思维导图: