题目:
封装一个学生类(Student):包括受保护成员:姓名、年龄、分数,完成其相关函数,以及show
在封装一个领导类(Leader):包括受保护成员:岗位、工资,完成其相关函数及show
由以上两个类共同把派生出学生干部类:引入私有成员:管辖人数,完成其相关函数以及show函数
在主程序中,测试学生干部类:无参构造、有参构造、拷贝构造、拷贝赋值、show
代码:
#include <iostream>
using namespace std;
class Student
{
protected:
string name;
int old;
double score;
public:
Student(){cout<<"Student::无参构造"<<endl;}
Student(string n,int o,double s):name(n),old(o),score(s){cout<<"Student::有参构造"<<endl;}
Student(const Student &other):name(other.name),old(other.old),score(other.score){cout<<"Student::拷贝构造"<<endl;}
Student &operator=(const Student &other)
{
this->name=other.name;
this->old=other.old;
this->score=other.score;
cout<<"Student::拷贝赋值"<<endl;
return *this;
}
~Student(){cout<<"Student::析构函数"<<endl;}
void show()
{
cout<<"********************"<<endl;
cout<<"Student::name="<<name<<endl;
cout<<"Student::old="<<old<<endl;
cout<<"Student::score="<<score<<endl;
cout<<"********************"<<endl;
}
};
class Leader
{
protected:
string job;
int money;
public:
Leader(){cout<<"Leader::无参构造"<<endl;}
Leader(string j,int m):job(j),money(m){cout<<"Leader::有参构造"<<endl;}
~Leader(){cout<<"Leader::析构函数"<<endl;}
Leader(const Leader &other):job(other.job),money(other.money){cout<<"Leader::拷贝构造"<<endl;}
Leader &operator=(const Leader &other)
{
this->job=other.job;
this->money=other.money;
cout<<"Leader::拷贝赋值"<<endl;
return *this;
}
void show()
{
cout<<"********************"<<endl;
cout<<"Leader::job="<<job<<endl;
cout<<"Leader::money="<<money<<endl;
cout<<"********************"<<endl;
}
};
class Student_leader:public Student,public Leader
{
protected:
int num;
public:
Student_leader(){cout<<"Student_leader::无参构造"<<endl;}
Student_leader(string n,int o,double s,string j,int m,int nu):Student(n,o,s),Leader(j,m),num(nu){cout<<"Student_leader::有参构造"<<endl;}
~Student_leader(){cout<<"Student_leader::析构函数"<<endl;}
Student_leader(const Student_leader &other):Student(other),Leader(other),num(other.num){cout<<"Student_leader::拷贝构造"<<endl;}
Student_leader &operator=(const Student_leader &other)
{
if(this!=&other)
{
this->num=other.num;
Student::operator=(other);
Leader::operator=(other);
}
cout<<"Student_leader::拷贝赋值"<<endl;
return *this;
}
void show()
{
cout<<"********************"<<endl;
cout<<"Student_leader::name="<<name<<endl;
cout<<"Student_leader::old="<<old<<endl;
cout<<"Student_leader::score="<<score<<endl;
cout<<"Student_leader::job="<<job<<endl;
cout<<"Student_leader::money="<<money<<endl;
cout<<"Student_leader::num="<<num<<endl;
cout<<"********************"<<endl;
}
};
int main()
{
Student_leader a1;
a1.show();
Student_leader a2("张三",19,77.5,"主管",200,5);
a2.show();
Student_leader a3=a2;
a3.show();
a1=a3;
a1.show();
return 0;
}
运行结果:
