写一个程序,定义一个抽象类Shape,由它派生3个类:Square(正方形)、Trapezoid(梯形)和Triangle三角形。用虚函数分别计算几种图形面积、并求它们的和。
时间: 2024-03-09 14:45:42 浏览: 164
利用虚函数计算各种图形面积
5星 · 资源好评率100%
好的,我可以帮你写这个程序。以下是代码:
```cpp
#include <iostream>
using namespace std;
class Shape {
public:
virtual double getArea() = 0; // 纯虚函数,求面积
};
class Square : public Shape {
private:
double length;
public:
Square(double l) {
length = l;
}
double getArea() {
return length * length;
}
};
class Trapezoid : public Shape {
private:
double upper, lower, height;
public:
Trapezoid(double u, double l, double h) {
upper = u;
lower = l;
height = h;
}
double getArea() {
return (upper + lower) * height / 2;
}
};
class Triangle : public Shape {
private:
double base, height;
public:
Triangle(double b, double h) {
base = b;
height = h;
}
double getArea() {
return base * height / 2;
}
};
int main() {
Shape *shapes[3];
shapes[0] = new Square(2.0);
shapes[1] = new Trapezoid(3.0, 4.0, 2.0);
shapes[2] = new Triangle(3.0, 4.0);
double totalArea = 0.0;
for (int i = 0; i < 3; i++) {
totalArea += shapes[i]->getArea();
}
cout << "总面积为:" << totalArea << endl;
return 0;
}
```
程序定义了一个抽象类`Shape`,它有一个纯虚函数`getArea()`,用于计算图形的面积。然后定义了三个派生类`Square`、`Trapezoid`和`Triangle`,它们分别计算正方形、梯形和三角形的面积。在`main()`函数中,创建了三个图形对象,并将它们存储在一个数组中。然后遍历数组,求出所有图形的面积之和并输出。
阅读全文