天天看点

C++面向对象程序设计之类的继承与派生

1.编写一个学生和教师数据输入和显示程序。其中,学生数据有编号、姓名、班级和成绩,教师数据有编号、姓名、职称和部门。要求将编号、姓名输入和显示设计成一个类Person;然后设计类Person的派生类:学生类Student和教师类Teacher:编写一个主函数,通过定义student、teacher的对象,完成相应功能。

#include <iostream>

#include <string>
using namespace std;
class person                                                 //定义一个类
{
public:                                                      //公用成员函数
	person(int  a, string s)                                //构造函数,参数为(学号和姓名)
	{
		number = a;                                          //
		name = s;
	}

	void display();
private:                                                     //私有成员
	int  number;
	string name;

};



void person::display()                                      //student 成员显示函数定义
{
	cout << "number:" << number<< endl;
	cout << "name:" << name << endl;          //输出班级和成绩信息
}




class student : public person                                //声明一个公有继承的派生类:student类
{
public:
	student(int  a, string s, int m, int n) :person(a, s)//定义student派生类的构造函数
	{
		Class = m;                                           //班级
		score = n;                                           //成绩

	}
	void dispay1(); 

private:
	int Class;                                            //班级
	int score;                                            //成绩
};

void student::dispay1()                                      //student 成员显示函数定义
{
	person::display();
	cout << "Class:" << Class << endl;
	cout << "score:" << score << endl;           //输出班级和成绩信息
}



class teacher :public person                                 //声明一个派生类teacher,公有继承
{
public:
	teacher(int a, string s, string m, string n) :person(a, s) //定义teacher派生类的构造函数
	{
		title = m;                                           //新增的参数,职位
		section = n;                                         //新增的参数,部门
	}
	void display2(); 

	//显示函数
private:
	string title;                                            //职位
	string section;                                          //部门


};

void teacher::display2()                                      //teacher的显示函数
{
	person::display();
	cout << "title:" << title << endl;
	cout << "section:" << section << endl;        //

}



int main()                                                  //主函数
{
	student stud( 19101,"liqiang",19,99);
	teacher teach(19012,"qinghua","doctor","CS");
	stud.dispay1();
	teach.display2(); 
	return 0;
}

           

运行如下:

C++面向对象程序设计之类的继承与派生