某学校对教师每月工资的计算规定如下:
工资=固定工资+课时补贴;
教授每课时50元;副教授每课时30元;讲师每课时20元。
定义教师抽象类,派生出不同职称的教师类,编写程序求若干个教师的月工资。
#include<iostream>
#include<string>
using namespace std;
class Teacher //基类
{
protected:
int no; //编号
string name; //姓名
float salary; //月薪总额
static int totalno; //教师目前编号最大值
float classlyrate; //每课时薪酬
float workhours; //每课时钱数
float monthlypay; //固定月工资
public:
Teacher()
{
no=totalno++; //输入的教师编号为目前最大编号加1
cout<<"教师姓名:";
cin>>name;
salary=0.0; //教师工资初始为零
}
~Teacher(){}
virtual void pay()=0; //计算月薪函数
virtual void display()=0; //输出教师信息函数
};
class Professor: public Teacher //派生类,教授
{
protected:
int level; //等级职位
public:
Professor() {
classlyrate=50; //每课时50元
cout<<name<<"本月工作课时:";
cin>>workhours;
cout<<"教授等级(1,2):";
cin>>level;
monthlypay=level==1?8000:7500;
}
void pay(){
salary=monthlypay+classlyrate*workhours;
}
void display(){
cout<<level<<"级教授: "<<name<<", 编号:";
cout<<no<<", 本月工资:"<<salary<<endl;
}
};
int Teacher::totalno=10000; //员工编号基数为10000
class AssProfessor:virtual public Teacher //派生类,副教授
{
public:
AssProfessor(){
classlyrate=30;
cout<<name<<"本月课时:";
cin>>workhours;
cout<<"副教授等级(1,2,3):";
cin>>level;
switch(level){
case 1:
monthlypay=7000;
break;
case 2:
monthlypay=6000;
break;
case 3:
monthlypay=5000;
break;
}
}
protected:
int level;
void pay(){
salary=monthlypay+classlyrate*workhours;
}
void display(){
cout<<level<<"级副教授: "<<name<<", 编号:";
cout<<no<<", 本月工资:"<<salary<<endl;
}
};
class Lecture:virtual public Teacher //派生类,讲师
{
public:
Lecture(){
classlyrate=20;
monthlypay=4500;
cout<<name<<"本月课时:";
cin>>workhours;
}
void pay(){
salary=monthlypay+classlyrate*workhours;
}
void display(){
cout<<"讲师: "<<name<<", 编号:";
cout<<no<<", 本月工资:"<<salary<<endl;
}
};
int main() //主函数
{
Professor p1;
Professor p2;
AssProfessor a1;
AssProfessor a2;
Lecture l;
Teacher* em[5]={&p1,&p2,&a1,&a2,&l};
cout<<"上述教职人员的基本信息为: "<<endl;
for(int i=0;i<5;i++)
{
em[i]->pay();
em[i]->display();
}
return 0;
}
相关知识:
对于包含纯虚函数的类为抽象类,它只能作为基类派生新类;
在基类中定义纯虚函数,方便主函数中依据赋值兼容原则用Teacher类型的指针数组来处理不同派生类的对象;
派生类包含基类的属性,同时具有自己的独特属性;