cpp定义一个抽象基类教师类Teacher由教师类派生出讲师教授副教授他们工资由基础工资加上课时和津贴求各自工资课抽象基类和各派生类均有一个公有成员函数Salary 用于计算各位教师的工资总额。
#include<iostream>
using namespace std;
// 抽象基类:教师类
class Teacher {
protected:
double basicSalary; // 基础工资
double teachingHours; // 课时
double allowance; // 津贴
public:
Teacher(double basicSalary, double teachingHours, double allowance)
: basicSalary(basicSalary), teachingHours(teachingHours), allowance(allowance) {}
// 纯虚函数,表示该函数在基类中没有具体实现,需要在派生类中实现
virtual double Salary() = 0; // 计算工资总额
};
// 讲师类
class Lecturer : public Teacher {
public:
Lecturer(double basicSalary, double teachingHours, double allowance)
: Teacher(basicSalary, teachingHours, allowance) {}
double Salary() {
return basicSalary + teachingHours + allowance;
}
};
// 教授类
class Professor : public Teacher {
public:
Professor(double basicSalary, double teachingHours, double allowance)
: Teacher(basicSalary, teachingHours, allowance) {}
double Salary() {
return basicSalary + teachingHours + allowance;
}
};
// 副教授类
class AssociateProfessor : public Teacher {
public:
AssociateProfessor(double basicSalary, double teachingHours, double allowance)
: Teacher(basicSalary, teachingHours, allowance) {}
double Salary() {
return basicSalary + teachingHours + allowance;
}
};
int main() {
Teacher* teacher1 = new Lecturer(5000, 100, 1000);
cout << "Lecturer's salary: " << teacher1->Salary() << endl;
Teacher* teacher2 = new Professor(8000, 120, 2000);
cout << "Professor's salary: " << teacher2->Salary() << endl;
Teacher* teacher3 = new AssociateProfessor(6000, 90, 1500);
cout << "Associate Professor's salary: " << teacher3->Salary() << endl;
delete teacher1;
delete teacher2;
delete teacher3;
return 0;
}
运行结果:
Lecturer's salary: 6100
Professor's salary: 10220
Associate Professor's salary: 7590
在上述代码中,定义了一个抽象基类Teacher,并在其中定义了纯虚函数Salary(),表示计算工资总额。然后派生出了三个子类Lecturer、Professor和AssociateProfessor,分别表示讲师、教授和副教授。这三个子类分别实现了Salary()函数,根据基础工资、课时和津贴计算出各自的工资总额。
在main函数中,通过创建指向Teacher类型的指针,并分别指向Lecturer、Professor和AssociateProfessor对象,调用Salary()函数计算各位教师的工资总额,并输出结果。
最后,记得在main函数结束前释放动态分配的内存空间。
原文地址: https://www.cveoy.top/t/topic/i9W5 著作权归作者所有。请勿转载和采集!