作业要求:
1.封装一个学生类(Student):包括受保护成员:姓名、年龄、分数,完成其相关函数及show
2.再封装一个领导类(Leader):包括受保护成员:岗位、工资,完成其相关函数及show
3.由以上两个类共同派生出学生干部类:引入私有成员:管辖人数,完成其相关函数及show
4.在主程序中,测试学生干部类:无参构造、有参构造、拷贝构造、拷贝赋值、show
实现过程:
#include <iostream>
using namespace std;
//封装一个学生类(Student):包括受保护成员:姓名、年龄、分数,完成其相关函数,以及show
//在封装一个领导类(Leader):包括受保护成员:岗位、工资,完成其相关函数及show
//由以上两个类共同把派生出学生干部类:引入私有成员:管辖人数,完成其相关函数以及show函数
//在主程序中,测试学生干部类:无参构造、有参构造、拷贝构造、拷贝赋值、show
class Student{
protected:
string name; //姓名
int age; //年龄
double score; //成绩
public:
Student(){} //无参构造函数
Student(string n, int a,int s):name(n),age(a),score(s){} //有参构造函数
~Student(){} //析构函数
Student(const Student &other):name(other.name), age(other.age),score(other.score){} //拷贝构造函数
Student &operator=(const Student &other){ //拷贝赋值函数
if(this != &other){ //判断是否是自身赋值
this->name = other.name;
this->age = other.age;
this->score = other.score;}
return *this;}
void show(){ //展示函数
cout<<"姓名="<<name<<endl;
cout<<"年龄="<<age<<endl;
cout<<"成绩="<<score<<endl;}};
class Leader{
protected:
string post; //岗位
double wages; //工资
public:
Leader(){} //无参构造函数
Leader( string p,double w):post(p),wages(w){} //有参构造函数
~Leader(){} //析构函数
Leader(const Leader &other):post(other.post), wages(other.wages){} //拷贝构造函数
Leader &operator=(const Leader &other){ //拷贝赋值函数
if(this != &other){ //判断是否是自身赋值
this->post = other.post;
this->wages = other.wages;}
return *this;}
void show(){ //展示函数
cout<<"岗位="<<post<<endl;
cout<<"工资="<<wages<<endl;}};
class Student_cadres:public Student, public Leader{
private:
int num; //管辖人数
public:
Student_cadres(){} //无参构造函数
Student_cadres(string n, int a, double s, string p, double w, int m):Student(n,a,s),Leader(p,w),num(m){} //有参构造函数
~Student_cadres(){} //析构函数
Student_cadres(const Student_cadres &other):Student(other),Leader(other),num(other.num){} //拷贝构造函数
Student_cadres &operator=(const Student_cadres &other){ //拷贝赋值函数
if(this != &other){ //判断是否是自身赋值
this->num = other.num;
Student::operator=(other); //调用父类的拷贝赋值函数
Leader::operator=(other);} //调用父类的拷贝赋值函数
return *this;}
void show(){ //展示函数
cout<<"姓名="<<name<<endl;
cout<<"年龄="<<age<<endl;
cout<<"成绩="<<score<<endl;
cout<<"岗位="<<post<<endl;
cout<<"工资="<<wages<<endl;
cout<<"管辖人数="<<num<<endl;}};
int main()
{
cout<<"无参构造s1"<<endl;
Student_cadres s1;
s1.show(); //string为空,int为随机,double为0
cout<<endl;
cout<<"有参构造s2"<<endl;
Student_cadres s2("李四",18,99.9,"经理",10000,10);
s2.show();
cout<<endl;
cout<<"拷贝构造s3"<<endl;
Student_cadres s3=s2;
s3.show();
cout<<endl;
cout<<"拷贝赋值s4"<<endl;
Student_cadres s4;
s4=s2;
s4.show();
cout<<endl;
cout<<"访问子类中的父类继承的函数"<<endl;
s4.Student::show();
s4.Leader::show();
return 0;
}
实现效果: