作业:
定义一个学生类(Student):私有成员属性(姓名、年龄、分数)、成员方法(无参构造、有参构造、析构函数、show函数)
再定义一个党员类(Party):私有成员属性(党组织活动,组织),成员方法(无参构造、有参构造、析构函数、show函数)。
由这两个类共同派生出学生干部类,私有成员属性(职位),成员方法(无参构造、有参构造、析构函数、show函数),使用学生干部类实例化一个对象,然后调用其show函数进行测试
#include <iostream>
using namespace std;
class Student
{
private:
string name;
int age;
float score;
public:
Student () {cout << "Stu::无参构造" << endl;}
Student (string n, int a, float s):name(n), age(a), score(s)
{
cout << "Stu::有参构造" << endl;
}
~Student()
{
cout << "Stu::析构函数" << endl;
}
void show()
{
cout << "name = " << name << endl;
cout << "age = " << age << endl;
cout << "score = " << score << endl;
}
//定义父类的拷贝构造
// Father(const Father &other): money(other.money), pwd(other.pwd), name(other.name)
// {
// cout << "Father::拷贝构造函数" << endl;
// }
//拷贝构造函数
Student(const Student &other): name(other.name), age(other.age), score(other.score)
{
cout << "Stu::拷贝构造函数" << endl;
}
};
class Party
{
private:
string OrgAct;
string Org;
public:
Party () {cout << "Party::无参构造" << endl;}
Party (string a, string o):OrgAct(a), Org(o)
{
cout << "Party::有参构造" << endl;
}
~Party()
{
cout << "Party::析构函数" << endl;
}
void show()
{
cout << "OrgAct = " << OrgAct << endl;
cout << "Org = " << Org << endl;
}
//定义拷贝构造函数
Party(const Party &other): OrgAct(other.OrgAct), Org(other.Org)
{
cout << "Party::拷贝构造函数" << endl;
}
};
class StuCad : public Student, Party
{
private:
string position;
public:
StuCad() {cout << "StuCad::无参构造" << endl;}
StuCad(string n, int a1, float s, string a2, string o, string p):Student(n, a1, s), Party(a2, o), position(p)
{
cout << "StuCad::有参构造" << endl;
}
~StuCad()
{
cout << "StuCad::析构函数" << endl;
}
//定义拷贝构造函数
StuCad(const StuCad &other): Student(other), Party(other), position(other.position)
{
cout << "StuCad::拷贝构造函数" << endl;
}
void show()
{
Student::show();
Party::show();
cout << "position = " << position << endl;
}
};
int main()
{
StuCad s1("t", 18, 99, "参观博物馆", "第一党组织", "党员");
cout << "******************************************" << endl;
s1.show();
cout << "******************************************" << endl;
return 0;
}
输出结果:
Stu::有参构造
Party::有参构造
StuCad::有参构造
******************************************
name = t
age = 18
score = 99
OrgAct = 参观博物馆
Org = 第一党组织
position = 党员
******************************************
StuCad::析构函数
Party::析构函数
Stu::析构函数