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;
}
運作如下: