最后一道大题题目再现
写一个person类 ,有姓名,性别,年龄。然后在此基础上派生 出教师类 和学生类。教师类 增加了以下数据:工号,职称,工资。学生类增加了以下数据成员:学号,专业,班级,入学成绩。要求在main函数中输出数据。
代码实现
cpp
#include <iostream>
#include <string>
using namespace std;
class Person{
public:
Person(string name1,string sex1,int age1)
{
name=name1; sex=sex1; age=age1;
}
void show()
{
cout<<"姓名:"<<name<<" ";
cout<<"性别:"<<sex<<" ";
cout<<"年龄:"<<age<<endl;
}
private:
string name;
string sex;
int age;
};
class Teacher:public Person{
public:
Teacher(string name1,string sex1,int age1,
string Tsno1,string title1,double wage1)
:Person(name1,sex1,age1)
{
Tsno=Tsno1; title=title1; wage=wage1;
}
void show(){
cout<<"Teacher:"<<endl;
Person::show();
cout<<"工号:"<<Tsno<<" ";
cout<<"职称:"<<title<<" ";
cout<<"工资:"<<wage<<endl;
}
private:
string Tsno;
string title;
double wage;
};
class Student:public Person{
public:
Student(string name1,string sex1,int age1,
string Ssno1,string speciality1,string Class1,double grade1)
:Person(name1,sex1,age1)
{
Ssno=Ssno1; speciality=speciality1; Class=Class1; grade=grade1;
}
void show(){
cout<<"Student:"<<endl;
Person::show();
cout<<"学号:"<<Ssno<<" ";
cout<<"专业:"<<speciality<<" ";
cout<<"班级:"<<Class<<" ";
cout<<"入学成绩:"<<grade<<endl;
}
private:
string Ssno;
string speciality;
string Class;
double grade;
};
int main()
{
Person P1("张三","男",30);
cout<<"Person:"<<endl;
P1.show();
Teacher T1("郑强强","男",63,"20240102","教授",10000);
T1.show();
Student S1("董辉辉","男",30,"20230102","计算机","二班",100);
S1.show();
return 0;
}
输出
cpp
Person:
姓名:张三 性别:男 年龄:30
Teacher:
姓名:郑强强 性别:男 年龄:63
工号:20240102 职称:教授 工资:10000
Student:
姓名:董辉辉 性别:男 年龄:30
学号:20230102 专业:计算机 班级:二班 入学成绩:100
--------------------------------
Process exited after 0.03635 seconds with return value 0
请按任意键继续. . .
注意细节
一个小细节,需要在头文件内包含string类。性别 "男" 或 "女" 如果用char类型会报错,因为 一个汉字=2字符。所有用string类型。以后只要有中文,通通用string。
最后
我在试卷上是没有把代码写完的。太长了~,而且真的不习惯手写代码~~