定义一个学生类(Student):私有成员属性(姓名、年龄、分数)、成员方法(无参构造、有参构造、析构函数、show函数)
再定义一个党员类(Party):私有成员属性(党组织活动,组织),成员方法
由这两个类共同派生出学生干部类,私有成员属性(职位),成员方法(无参构造、有参构造、析构函数、show函数),使用学生干部类实例化一个对象,然后调用其show函数进行测试
#include <iostream>
using namespace std;
class Stu //定义学生类
{
private:
string name; //姓名
int age; //年龄
double score;//分数
public:
Stu()//无参构造
{
cout << "Stu::无参构造" << endl;
}
Stu(string name, int age, double score):name(name), age(age), score(score)//有参构造
{
cout << "Stu::有参构造" << endl;
}
~Stu()//析构函数
{
cout << "Stu::析构函数" << endl;
}
void show()//show函数
{
cout << "name = " << name << endl;
cout << "age = " << age << endl;
cout << "score = " << score << endl;
}
};
class Party //定义党员类
{
private:
string act; //党组织活动
string org; //组织
public:
Party()//无参构造
{
cout << "Party::无参构造" << endl;
}
Party(string act, string org):act(act), org(org)//有参构造
{
cout << "Party::有参构造" << endl;
}
~Party()//析构函数
{
cout << "Party::析构函数" << endl;
}
void show()//show函数
{
cout << "act = " << act << endl;
cout << "org = " << org << endl;
}
};
//由这两个类共同派生出学生干部类
class Leader: public Stu, public Party
{
private:
string post;
public:
Leader()//无参构造
{
cout << "Leader::无参构造" << endl;
}
Leader(string name, int age, double score, string act, string org, string post):\
Stu(name, age, score), Party(act, org), post(post)//有参构造
{
cout << "Leader::有参构造" << endl;
}
~Leader()//析构函数
{
cout << "Leader::析构函数" << endl;
}
void show()//show函数
{
Stu::show();
Party::show();
cout << "post = " << post << endl;
//私有成员,继承后子类无法访问
//cout << "name = " << name << endl;
//cout << "age = " << age << endl;
//cout << "score = " << score << endl;
//cout << "act = " << act << endl;
//cout << "org = " << org << endl;
}
};
int main()
{
Leader l("zhangsan", 19, 99.5, "aa", "bb", "cc");
l.show();
return 0;
}