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

本文介绍了一个简单的学生和教师信息管理程序的设计与实现。程序使用C++编写,通过类的继承来实现学生和教师数据的输入与显示。学生数据包括编号、姓名、班级和成绩;教师数据则包括编号、姓名、职称和部门。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}

运行如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值