c++中多重继承应用
题目:
封装一个学生类(Student):包括受保护成员:姓名、年龄、分数,完成其相关函数,以及show
在封装一个领导类(Leader):包括受保护成员:岗位、工资,完成其相关函数及show
由以上两个类共同把派生出学生干部类:引入私有成员:管辖人数,完成其相关函数以及show函数
在主程序中,测试学生干部类:无参构造、有参构造、拷贝构造、拷贝赋值、show
程序:
#include <iostream>
using namespace std;
class Student
{
protected:
string name;
int age;
double score;
public:
Student(){cout<<"Stu::无参构造"<<endl;}
Student(string n,int a,double s):name(n),age(a),score(s)
{
cout <<"Stu::有参构造"<<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)
{
if(this != &other)
{
this->name = other.name;
this->age = other.age;
this->score = other.score;
}
cout<<"Student::拷贝赋值函数"<<endl;
return *this;
}
void show()
{
cout<<"stu.name:"<<name<<endl;
cout<<"stu.age:"<<age<<endl;
cout<<"stu.score:"<<score<<endl;
}
};
class Leader
{
protected:
string position;
int wage;
public:
Leader(){cout<<"Leader::无参构造"<<endl;}
Leader(string p,int w):position(p),wage(w)
{
cout <<"Leader::有参构造"<<endl;
}
//析构函数
~Leader(){cout<<"Leader::析构函数"<<endl;}
//拷贝构造函数
Leader(const Leader&other):position(other.position),wage(other.wage)
{
cout<<"Leader::拷贝构造函数"<<endl;
}
//父类的拷贝赋值函数
Leader &operator=(const Leader&other)
{
if(this != &other)
{
this->position= other.position;
this->wage= other.wage;
}
cout<<"Student::拷贝赋值函数"<<endl;
return *this;
}
void show()
{
cout<<"Leader.name:"<<position<<endl;
cout<<"Leader.age:"<<wage<<endl;
}
};
class cadre:public Student,public Leader
{
private:
int num;
public:
cadre(){cout<<"cadre::无参构造"<<endl;}
cadre(string n,int a,double s,string p,int w,int n1):Student(n,a,s),Leader(p,w),num(n1)
{
cout <<"cadre::有参构造"<<endl;
}
//子类析构函数
~cadre(){
cout<<"cadre::析构函数"<<endl;
}
//子类拷贝构造函数
cadre (const cadre&other):Student(other),Leader(other),num(other.num)
{
cout<<"cadre::拷贝构造"<<endl;
}
//子类的拷贝赋值函数
cadre &operator=(const cadre&other)
{
if(this != &other)
{
this->num = other.num;
Student::operator=(other); //调用父类的拷贝赋值函数,完成对继承下来成员的赋值
Leader::operator=(other);
}
cout<<"cadre::拷贝赋值函数"<<endl;
return *this;
}
void show()
{
cout<<"cadre::name = "<<this->name<<endl;
cout<<"cadre::age = "<<age<<endl;
cout<<"cadre::score = "<<score<<endl;
cout<<"cadre::position = "<<position<<endl;
cout<<"cadre::wage = "<<wage<<endl;
cout<<"cadre::num = "<<num<<endl;
}
};
int main()
{
//无参构造
cadre c1;
cout<<"***************************"<<endl;
//有参构造
cadre c2("wxy",20,99,"团支书",100,30);
c2.show();
cout<<"***************************"<<endl;
//拷贝构造
cadre c3=c2;
c3.show();
cout<<"***************************"<<endl;
//拷贝赋值
cadre c4;
c4=c2;
c4.show();
return 0;
}
运行效果: