1.父类_1
定义一个学生类(Student):私有成员属性(姓名、年龄、分数)、成员方法(无参构造、有参构造、析构函数、 show函数)再定义一个党员类(Party)∶
2.父类_2
私有成员属性(党组织活动,组织),成员方法(无参构造、有参构造、析构函数、show函数)。
3.子类_3
由这两个类共同派生出学生干部类,私有成员属性(职位),成员方法(无参构造、有参构造、析构函数、show函数,使用学生干部类实例化一个对象,然后调用其show函数进行测试,拷贝构造,赋值构造
#include <iostream>
using namespace std;
//student
class student
{
private:
string name; //姓名
int * age; //年纪 指针
double sex; //分数
public:
student(){cout<<"student::无参构造"<<endl;}
student(string n,int a,double s):name(n),age(new int(a) ),sex(s){cout<<"Student::有参构造"<<endl;}
~student()
{
delete age; //释放堆区空间
cout<<"student::析构函数"<<endl;
}
//拷贝构造
student(const student & other):name(other.name),age(new int (*(other.age))),sex(other.sex){cout<<"Student::拷贝构造"<<endl;}
//赋值构造
student & operator=(const student & other)
{
this->name=other.name;
*(this->age)=*(other.age);
this->sex=other.sex;
cout<<"student::赋值构造"<<endl;
return *this;
}
void show()
{
cout<<"name="<<name<<" age="<<*age<<" sex="<<sex<<endl;
}
};
//patry
class patry
{
private:
string activi; //活动
string organ; //组织
public:
patry(){cout<<"patry::无参构造"<<endl;}
patry(string a,string o):activi(a),organ(o){cout<<"patry::有参构造"<<endl;}
~patry(){cout<<"patry::析构函数"<<endl;}
//拷贝构造
patry (const patry & other):activi(other.activi),organ(other.organ){cout<<"patry::拷贝构造"<<endl;}
//拷贝赋值
patry & operator=(const patry &other)
{
this->activi=other.activi;
this->organ=other.organ;
cout<<"patry::赋值构造"<<endl;
return *this;
}
void show()
{
cout<<"activi="<<activi<<" organ="<<organ<<endl;
}
};
//patry&student=cadre
class cadre:public student,public patry
{
private:
string job; //职位
public:
cadre(){cout<<"cadre::无参构造"<<endl;}
cadre(string name,int age,double sex,string activi,string organ,string j)://换行
student(name,age,sex),patry(activi,organ),job(j)
{cout<<"cadre::有参构造"<<endl;}
~cadre(){cout<<"cadre::析构函数"<<endl;}
//子类的拷贝构造
cadre(const cadre &other):student(other),patry(other),job(other.job){cout<<"cadre::拷贝构造"<<endl;}
//父类的拷贝赋值
cadre &operator=(const cadre &other)
{
student::operator=(other);
patry::operator=(other);
this->job=other.job;
cout<<"cadre::拷贝赋值"<<endl;
return *this;
}
void show()
{
student::show();
patry::show();
cout<<"job="<<job<<endl;
}
};
int main()
{
//调用有参构造
cadre s1("张三",18,100,"LOL总决赛","中国电竞部","野王");
//输出
s1.show();
//拷贝构造
cadre s2=s1;
s2.show();
//拷贝赋值
cadre s3(s2);
s3=s1;
s3.show();
return 0;
}