代码实现
#include <iostream>
using namespace std;
class Student
{
protected:
//学生姓名
string name;
//学生年龄
int age;
//学生成绩
double score;
public:
//无参构造函数
Student()
{
cout<< "Student无参构造函数" <<endl;
}
//有参构造函数
Student(string n, int a, double s):name(n),age(a),score(s)
{
cout<< "Student有参构造函数" <<endl;
}
//拷贝构造函数
Student (const Student &other):name(other.name),age(other.age),score(other.score)
{
cout<< "Student拷贝构造函数" << endl;
}
//析构函数
~Student()
{
cout<< "Student析构函数 " << this<< 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 << "----------Student Message----------" << endl;
cout << "Student ::name = " << name << endl;
cout << "Student ::age = " << age << endl;
cout << "Student ::score = " << score << endl;
}
};
class Teacher
{
protected:
//教师职称
string rank;
//教师年龄
int age;
public:
//无参构造函数
Teacher()
{
cout<< "Teacher无参构造函数" <<endl;
}
//有参构造函数
Teacher(string r, int a):rank(r),age(a)
{
cout<< "Teacher有参构造函数" <<endl;
}
//拷贝构造函数
Teacher(const Teacher &other):rank(other.rank),age(other.age)
{
cout<< "Teacher拷贝构造函数" << endl;
}
//析构函数
~Teacher()
{
cout<< "Teacher析构函数 " << this<< endl;
}
//拷贝赋值函数
Teacher &operator=(const Teacher &other)
{
if(this != &other)
{
this->rank = other.rank;
this->age = other.age;
}
cout<< "Teacher拷贝赋值函数" << endl;
return *this;
}
void show()
{
cout << "----------Teacher Message----------" << endl;
cout << "Teacher ::rank = " << rank << endl;
cout << "Teacher ::age = " << age << endl;
}
};
//研究生类
class Graduate : public Student,public Teacher
{
protected:
string sex;
public:
//无参构造函数
Graduate()
{
cout<< "Graduate无参构造函数" <<endl;
}
//有参构造函数
Graduate(string s_n, int s_a, double s_s , string t_r, int t_a,string s):Student(s_n,s_a,s_s), Teacher(t_r,t_a),sex(s)
{
cout<< "Graduate有参构造函数" <<endl;
}
//拷贝构造函数
Graduate(const Graduate &other):Student(other),Teacher(other),sex(other.sex)
{
cout<< "Graduate拷贝构造函数" << endl;
}
//析构函数
~Graduate()
{
cout<< "Graduate析构函数 " << this<< endl;
}
//拷贝赋值函数
Graduate &operator=(const Graduate &other)
{
if(this != &other)
{
this->sex = other.sex;
Student::operator=(other);
Teacher::operator=(other);
}
cout<< "Graduate拷贝赋值函数" << endl;
return *this;
}
void show()
{
cout << "-------Graduate Message Show-------" << endl;
Teacher::show();
Student::show();
cout << "Graduate::sex = "<< sex << endl;
cout << "-----------------------------------" << endl;
}
};
int main()
{
cout<< "有参构造研究生对象" <<endl;
Graduate g1("lisi", 25, 89.5, "教授", 59, "nan");
g1.show();
cout<< "无参构造研究生对象,通过拷贝复制函数赋值" <<endl;
Graduate g2;
g2 = g1;
g2.show();
cout<< "拷贝构造研究生对象" <<endl;
Graduate g3(g1);
g3.show();
return 0;
}