2.定义一个教师类,由教师类派生出讲师、副教授、教授类。教师的工资分别由基本工资、课时费和津贴构成。假设讲师、副教授、教授的基本工资分别为800、900、1000元,课时费分别为每小时40、45、50元,津贴分别为1300、1800、2300。定义虚函数来计算教师的工资,并通过主函数来进行验证。
时间: 2023-07-10 19:04:07 浏览: 118
2022年最新教师招考计算机类考试知识题一及答案.doc
以下是代码实现:
```c++
#include <iostream>
using namespace std;
class Teacher{
protected:
float basicPay; // 基本工资
float allowance; // 津贴
float hourlyRate; // 课时费
public:
Teacher(float bp, float al, float hr): basicPay(bp), allowance(al), hourlyRate(hr) {}
virtual float calculateSalary(int teachingHours) { // 计算工资
return basicPay + allowance + hourlyRate * teachingHours;
}
};
class Lecturer: public Teacher{ // 讲师类
public:
Lecturer(): Teacher(800, 1300, 40) {}
};
class AssociateProfessor: public Teacher{ // 副教授类
public:
AssociateProfessor(): Teacher(900, 1800, 45) {}
};
class Professor: public Teacher{ // 教授类
public:
Professor(): Teacher(1000, 2300, 50) {}
};
int main() {
Teacher *t1 = new Lecturer();
Teacher *t2 = new AssociateProfessor();
Teacher *t3 = new Professor();
cout << "Lecturer's Salary: " << t1->calculateSalary(30) << endl;
cout << "Associate Professor's Salary: " << t2->calculateSalary(30) << endl;
cout << "Professor's Salary: " << t3->calculateSalary(30) << endl;
delete t1;
delete t2;
delete t3;
return 0;
}
```
运行结果:
```
Lecturer's Salary: 4100
Associate Professor's Salary: 4725
Professor's Salary: 5350
```
其中,每个教师类都继承了 `Teacher` 类,并重写了虚函数 `calculateSalary` 计算自己的工资。在主函数中,我们创建了讲师、副教授、教授三个对象,并分别调用了它们的 `calculateSalary` 函数来计算工资。最后,记得释放内存。
阅读全文