实验八、多态 实验目的:(1)了解多态的基本原理及分类 (2)掌握虚函数和纯虚函数的概念及定义方法 实验要求:某学校对教师每月工资的计算公式如下:固定工资+额外补贴。教授的固定工资为5000元,每个课时补贴50元;副教授的固定工资为3000元,每个课时补贴为30元;讲师的固定工资为2000元,每个课时补20元。定义教师抽象类,派生不同职称的教师类,编写程序求若干教师的月工资。#include <iostream> #include<string> using namespace std; class Teacher { public: virtual void salary() = 0; void Putsalary() { salary(); } }; class Professor :public Teacher { public: string id; int wage; int keshi; virtual void salary(int sal) { sal = wage + keshi * 50; cout << "工资为:" << sal << endl; } Professor(string id,int wage, int keshi) :id(id),wage(wage),keshi(keshi) {}; }; void test01(Teacher*Tea) { Tea->Putsalary(); } void test02() { test01(new Professor); } int main() { }根据这个实验写的代码问题在哪里?
时间: 2024-03-24 07:41:01 浏览: 21
代码存在几个问题:
1. 在定义教师抽象类时,应该将固定工资和每个课时补贴作为类的成员变量,并将salary()函数声明为纯虚函数,具体计算工资的方法应该在派生类中实现。
2. 在Professor类中,应该重写salary()函数而不是定义一个新的带参数的salary()函数,因为在Teacher抽象类中已经声明了纯虚函数salary()。
3. 在test02()函数中,应该传入一个Professor类的对象而不是一个Teacher类的对象。
4. 在main()函数中应该创建多个不同职称的教师对象,并调用test01()函数计算他们的月工资。
下面是修改后的代码:
```c++
#include <iostream>
#include <string>
using namespace std;
class Teacher {
public:
int fixed_salary; // 固定工资
int subsidy; // 每个课时补贴
virtual void salary() = 0; // 纯虚函数
};
class Professor : public Teacher {
public:
string id;
int keshi;
Professor(string id) : id(id) {
fixed_salary = 5000;
subsidy = 50;
}
void salary() {
int sal = fixed_salary + keshi * subsidy;
cout << id << "的工资为:" << sal << endl;
}
};
class AssociateProfessor : public Teacher {
public:
string id;
int keshi;
AssociateProfessor(string id) : id(id) {
fixed_salary = 3000;
subsidy = 30;
}
void salary() {
int sal = fixed_salary + keshi * subsidy;
cout << id << "的工资为:" << sal << endl;
}
};
class Lecturer : public Teacher {
public:
string id;
int keshi;
Lecturer(string id) : id(id) {
fixed_salary = 2000;
subsidy = 20;
}
void salary() {
int sal = fixed_salary + keshi * subsidy;
cout << id << "的工资为:" << sal << endl;
}
};
void test01(Teacher* tea) {
tea->salary();
}
int main() {
Teacher* tea1 = new Professor("001");
tea1->keshi = 80;
Teacher* tea2 = new AssociateProfessor("002");
tea2->keshi = 60;
Teacher* tea3 = new Lecturer("003");
tea3->keshi = 40;
test01(tea1);
test01(tea2);
test01(tea3);
delete tea1;
delete tea2;
delete tea3;
return 0;
}
```