作业需求:
封装一个学生类(Student):包括受保护成员:姓名、年龄、分数,完成其相关函数,以及show
在封装一个领导类(Leader):包括受保护成员:岗位、工资,完成其相关函数及show
由以上两个类共同把派生出学生干部类:引入私有成员:管辖人数,完成其相关函数以及show函数
在主程序中,测试学生干部类:无参构造、有参构造、拷贝构造、拷贝赋值、show
实现过程:
#include <iostream>
using namespace std;
class stu
{
protected:
string name;
int age;
int sorce;
public:
stu() {cout<<"stu::无参构造"<<endl;}
stu(string n,int a,int s):name(n),age(a),sorce(s){cout<<"stu::有参构造"<<endl;}
~stu(){cout<<"stu::析构函数"<<endl;}
stu(const stu &s):name(s.name),age(s.age),sorce(s.sorce){cout<<"stu::拷贝构造函数"<<endl;}
stu &operator=(const stu &s)
{
if(this != &s)
{
this->age=s.age;
this->name=s.name;
this->sorce=s.sorce;
}
cout<<"stu::拷贝赋值函数"<<endl;
return *this;
}
void show()
{
cout<<"name = "<<name<<endl;
cout<<"age = "<<age<<endl;
cout<<"sorce = "<<sorce<<endl;
}
};
class leader
{
protected:
string post;
double wages;
public:
leader() {cout<<"leader::无参构造"<<endl;}
leader(string p,double w):post(p),wages(w){cout<<"leader::有参构造"<<endl;}
~leader(){cout<<"leader::析构函数"<<endl;}
leader(const leader &l):post(l.post),wages(l.wages){cout<<"leader::拷贝构造函数"<<endl;}
leader &operator=(const leader &l){
if(this != &l)
{
this->post=l.post;
this->wages=l.wages;
}
cout<<"leader::拷贝赋值函数"<<endl;
return *this;
}
void show()
{
cout<<"post = "<<post<<endl;
cout<<"wages = "<<wages<<endl;
}
};
class cadres :public stu,public leader
{
private:
int member;
public:
cadres() {cout<<"cadres::无参构造"<<endl;}
cadres(string n,int a,int s,string p,double w,int m):stu( n, a, s),leader( p, w),member(m){cout<<"cadres::有参构造"<<endl;}
~cadres(){cout<<"cadres::析构函数"<<endl;}
cadres(const cadres &c):stu(c),leader(c),member(c.member){cout<<"cadres::拷贝构造函数"<<endl;}
cadres &operator=(const cadres &c)
{
if(this != &c)
{
this->member=c.member;
stu::operator=(c);
leader::operator=(c);
}
cout<<"cadres::拷贝赋值函数"<<endl;
return *this;
}
void show()
{
stu::show();
leader::show();
cout<<"member = "<<member<<endl;
}
};
int main()
{
cadres s1;
s1.show();
cadres s2("wuch",18,100,"学生会会长",1000,20);
s2.show();
cadres s3=s2;
s3.show();
cadres s4;
s4=s2;
s4.show();
return 0;
}
实验结果:
![](https://i-blog.csdnimg.cn/blog_migrate/4dfcf1b6a7dd1b2260a21b9d48904da4.png)