目录
多重继承:
概念:一个类可以由多个类共同派生出来,那个该类会继承多个类的所有成员,并且拥有所有类的特征。
定义格式:
class 类名:继承方式1 父类1, 继承方式2 父类2,。。。,继承方式n,父类n
{ 子类扩充成员; };
示例功能:
封装一个学生类(Student):包括受保护成员:姓名、年龄、分数,完成其相关函数,以及show
在封装一个领导类(Leader):包括受保护成员:岗位、工资,完成其相关函数及show
由以上两个类共同把派生出学生干部类:引入私有成员:管辖人数,完成其相关函数以及show函数
在主程序中,测试学生干部类:无参构造、有参构造、拷贝构造、拷贝赋值、show
展示代码
#include <iostream>
using namespace std;
class Student
{
protected:
string name;
int age;
double score;
public:
Student() {cout <<"Student::无参构造"<<endl;} //无参构造
Student(string n,int a,double s):name(n),age(a),score(s){cout <<"Student::有参构造"<<endl;} //有参构造
~Student(){cout <<"Student::析构函数"<<endl;} //析构函数
Student(const Student &other):name(other.name),age(other.age),score(other.score)//拷贝构造函数
{
cout << "Student::拷贝构造函数"<<endl;
}
Student &operator=(const Student &other) //拷贝赋值函数
{
name=other.name;
age=other.age;
score=other.score;
cout << "Student::拷贝赋值函数"<<endl;
return *this;
}
void show()
{
cout << "name= " << name<<endl;
cout << "age= " << age <<endl;
cout << "score= "<< score<<endl;
}
};
class Leader
{
protected:
string post; //岗位
double wage; //工资
public:
Leader() {cout <<"Leader::无参构造"<<endl;} //无参构造
Leader(string p,double w):post(p),wage(w){cout <<"Leader::有参构造"<<endl;} //有参构造
~Leader(){cout <<"Leader::析构函数"<<endl;} //析构函数
Leader(const Leader &other):post(other.post),wage(other.wage) //拷贝构造函数
{
cout << "Leader::拷贝构造函数"<<endl;
}
Leader &operator=(const Leader &other) //拷贝赋值函数
{
post=other.post;
wage=other.wage;
cout << "Leader::拷贝赋值函数"<<endl;
return *this;
}
void show()
{
cout << "post= " << post <<endl;
cout << "wage= " << wage <<endl;
}
};
class Cadre:public Student,public Leader
{
private:
int Lnum;
public:
Cadre() {} //无参构造
Cadre(string n,int a,double s,string p,double w,int L):Student(n,a,s),Leader(p,w),Lnum(L){} //有参构造
~Cadre(){cout <<"Cadre::析构函数"<<endl;} //析构函数
Cadre(const Cadre &other):Student(other),Leader(other),Lnum(other.Lnum)//调用父类的拷贝构造函数 //拷贝构造函数
{
cout <<"Cadre::拷贝构造函数"<<endl;
}
Cadre &operator=(const Cadre &other)
{
//调用Student的拷贝赋值函数
if(this!=&other) //禁止自身赋值
{
Student::operator=(other);
Leader::operator=(other);
Lnum=other.Lnum;
cout <<"Cadre::拷贝赋值函数"<<endl;
}
return *this;
}
void show()
{
cout << "name= " << name<<endl;
cout << "age= " << age <<endl;
cout << "score= "<< score<<endl;
cout << "post= " << post <<endl;
cout << "wage= " << wage <<endl;
cout << "Lnum= " << Lnum <<endl;
}
};
int main()
{
cout << "欢迎来到多重继承" << endl;
//无参构造
Cadre c1;
//有参构造
Cadre c2("wxy",18,99.5,"团长",200,23);
//拷贝构造
Cadre c3(c2);
c3.show();
//拷贝赋值
Cadre c4;
c4=c3;
//show
c4.show();
return 0;
}
实现结果