一、
二、
#include <iostream>
using namespace std;
//封装 动物 类
class Animal
{
private://私有
string name;
string color;
int *age;
public://公共
Animal(){}//无参构造函数
Animal(string name,string color,int age):name(name),color(color),age(new int(age))
{
cout << "父类有参构造函数" << endl;
}
~Animal()
{
cout << "父类析构函数" << endl;
}
// 赋值兼容规则
// 1. 子类对象可以初始化基类的引用
// 2. 子类对象的地址 可以赋值给 父类的指针 eg: Person *p = &other
// 3. 子类的对象可以初始化基类的对象
Animal(const Animal &other):name(other.name),color(other.color),age(new int(*other.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(){}
Dog(int count,string name ,string color,int age):Animal(name,color,age),count(new int(count))
{
cout << "子类有参构造函数" << endl;
}
~Dog()
{
cout << "子类析构函数" << endl;
}
Dog(const Dog &other):Animal(other),count(new int(*other.count))
{
cout << "子类拷贝构造函数" << endl;
}
Dog &operator=(const Dog &other)
{
if(this != &other)
{
Animal::operator=(other);
count = new int(*other.count);
}
cout << "子类拷贝赋值函数" << endl;
return *this;
}
void speak()
{
cout << "汪汪汪" << endl;
}
};
int main()
{
Dog d1;
Dog d2(4,"dog","yellow",2);
Dog d3(d2);
d1 = d3;
return 0;
}
三、
#include <iostream>
using namespace std;
//封装 动物 类
class Animal
{
private:
string name;//动物名字
public:
Animal(){};//无参构造函数
Animal(string name):name(name)
{
cout << "父类有参构造函数" << endl;
}
virtual void perform()//构造虚函数
{
cout << "我是讲解员" << endl;
}
};
//封装 大象 类
class Elephant:public Animal
{
private:
string name;
public:
Elephant(){};//无参构造函数
Elephant(string n1,string n2):Animal(n1),name(n2)
{
cout << "子类1构造函数" << endl;
}
void perform()
{
cout << "大象大象大象" << endl;
}
};
//封装 狮子 类
class Lion:public Animal
{
private:
string name;
public:
Lion(){};//无参构造函数
Lion(string n1,string n2):Animal(n1),name(n2)
{
cout << "子类1构造函数" << endl;
}
void perform()
{
cout << "狮子狮子狮子" << endl;
}
};
//封装 猴子 类
class Money:public Animal
{
private:
string name;
public:
Money(){};//无参构造函数
Money(string n1,string n2):Animal(n1),name(n2)
{
cout << "子类1构造函数" << endl;
}
void perform()
{
cout << "猴子猴子猴子" << endl;
}
};
int main()
{
Elephant a("elephant","大象");
Animal *p = &a;
p->perform();
Lion b("lion","狮子");
p = &b;
p->perform();
Money c("Money","猴子");
p = &c;
p->perform();
return 0;
}