定义一个教师类,由教师类派生出讲师、副教授、教授类。教师的工资分别由基本工资、课时费和津贴构成。假设讲师、副教授、教授的基本工资分别为800、900、1000元,课时费分别为每小时40、45、50元,津贴分别为1300、1800、2300。定义虚函数来计算教师的工资,并通过主函数来进行验证。
时间: 2023-07-10 14:04:02 浏览: 146
类的派生——虚函数
以下是教师类及其派生类的定义:
```c++
#include <iostream>
using namespace std;
class Teacher {
protected:
float basicSalary; // 基本工资
float allowance; // 津贴
float hourlyFee; // 课时费
public:
Teacher(float bs, float al, float hf) : basicSalary(bs), allowance(al), hourlyFee(hf) {}
virtual float getSalary() { // 虚函数
return basicSalary + allowance;
}
};
class Lecturer : public Teacher {
public:
Lecturer() : Teacher(800, 1300, 40) {}
float getSalary() { // 重写虚函数
return basicSalary + allowance + hourlyFee * 40;
}
};
class AssociateProfessor : public Teacher {
public:
AssociateProfessor() : Teacher(900, 1800, 45) {}
float getSalary() { // 重写虚函数
return basicSalary + allowance + hourlyFee * 45;
}
};
class Professor : public Teacher {
public:
Professor() : Teacher(1000, 2300, 50) {}
float getSalary() { // 重写虚函数
return basicSalary + allowance + hourlyFee * 50;
}
};
```
在主函数中,我们可以创建各种教师的对象并调用其方法来计算工资。
```c++
int main() {
Teacher* t1 = new Lecturer();
Teacher* t2 = new AssociateProfessor();
Teacher* t3 = new Professor();
cout << "Lecturer's salary: " << t1->getSalary() << endl;
cout << "Associate Professor's salary: " << t2->getSalary() << endl;
cout << "Professor's salary: " << t3->getSalary() << endl;
delete t1;
delete t2;
delete t3;
return 0;
}
```
输出结果如下:
```
Lecturer's salary: 4900
Associate Professor's salary: 6075
Professor's salary: 7850
```
阅读全文