编写一个程序,定义抽象基类Shape,由它派生出5个派生类:Circle、Square、Rectangle、Trapezoid、Triangle。用虚函数分别计算几种图形面积,并求它们之和。2.某学校对教师每月工资的计算规定如下:固定工资+课时补贴。教授的固定工资为5000元,每个课时补贴50元。副教授的固定工资为3000元,每个课时补贴30元。讲师的固定工资为2000元,每个课时补贴20元。定义教师抽象类,派生不同职称的教师类,编写程序求若干个教师的月工资
时间: 2024-03-07 13:46:48 浏览: 151
好的,这是两个问题,我分别回答。
第一个问题,可以参考下面的代码实现:
```cpp
#include <iostream>
using namespace std;
class Shape {
public:
virtual double area() = 0;
};
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) {
radius = r;
}
virtual double area() {
return 3.14 * radius * radius;
}
};
class Square : public Shape {
private:
double side;
public:
Square(double s) {
side = s;
}
virtual double area() {
return side * side;
}
};
class Rectangle : public Shape {
private:
double length, width;
public:
Rectangle(double l, double w) {
length = l;
width = w;
}
virtual double area() {
return length * width;
}
};
class Trapezoid : public Shape {
private:
double upper_base, lower_base, height;
public:
Trapezoid(double ub, double lb, double h) {
upper_base = ub;
lower_base = lb;
height = h;
}
virtual double area() {
return (upper_base + lower_base) * height / 2;
}
};
class Triangle : public Shape {
private:
double base, height;
public:
Triangle(double b, double h) {
base = b;
height = h;
}
virtual double area() {
return base * height / 2;
}
};
int main() {
Shape *shapes[5];
shapes[0] = new Circle(2.0);
shapes[1] = new Square(3.0);
shapes[2] = new Rectangle(4.0, 5.0);
shapes[3] = new Trapezoid(3.0, 5.0, 4.0);
shapes[4] = new Triangle(4.0, 3.0);
double total_area = 0.0;
for (int i = 0; i < 5; i++) {
total_area += shapes[i]->area();
}
cout << "Total area: " << total_area << endl;
return 0;
}
```
第二个问题,可以参考下面的代码实现:
```cpp
#include <iostream>
using namespace std;
class Teacher {
public:
virtual double get_salary() = 0;
};
class Professor : public Teacher {
public:
virtual double get_salary() {
return 5000.0;
}
};
class AssociateProfessor : public Teacher {
public:
virtual double get_salary() {
return 3000.0;
}
};
class Lecturer : public Teacher {
public:
virtual double get_salary() {
return 2000.0;
}
};
int main() {
Teacher *teachers[3];
teachers[0] = new Professor();
teachers[1] = new AssociateProfessor();
teachers[2] = new Lecturer();
double total_salary = 0.0;
for (int i = 0; i < 3; i++) {
int hours;
cout << "Please input the hours of teacher " << i + 1 << ": ";
cin >> hours;
total_salary += teachers[i]->get_salary() + hours * (i + 1) * 10.0;
}
cout << "Total salary: " << total_salary << endl;
return 0;
}
```
注意:上述代码只是提供了一种实现方式,并不代表是最优解,可以根据实际情况进行修改和优化。
阅读全文