写一个程序,定义抽象类Shape,由它派生出5个派生类:Circle(圆),Square(正方形),Rectangle(矩形),Trapezoid(梯形),Triangle(三角形),用虚函数area()分别计算几种图形的面积,并求他们的和,要求使用基类指针数组,使它的每个元素都指向一个派生类对象
时间: 2024-02-22 13:56:05 浏览: 94
好的,以下是这个程序的代码实现:
```c++
#include <iostream>
using namespace std;
class Shape {
public:
virtual double area() = 0;
};
class Circle : public Shape {
private:
double r;
public:
Circle(double r) : r(r) {}
double area() {
return 3.14159 * r * r;
}
};
class Square : public Shape {
private:
double s;
public:
Square(double s) : s(s) {}
double area() {
return s * s;
}
};
class Rectangle : public Shape {
private:
double l, w;
public:
Rectangle(double l, double w) : l(l), w(w) {}
double area() {
return l * w;
}
};
class Trapezoid : public Shape {
private:
double a, b, h;
public:
Trapezoid(double a, double b, double h) : a(a), b(b), h(h) {}
double area() {
return (a + b) * h / 2;
}
};
class Triangle : public Shape {
private:
double a, b, c;
public:
Triangle(double a, double b, double c) : a(a), b(b), c(c) {}
double area() {
double p = (a + b + c) / 2;
return sqrt(p * (p - a) * (p - b) * (p - c));
}
};
int main() {
Shape* shapes[5];
shapes[0] = new Circle(2);
shapes[1] = new Square(3);
shapes[2] = new Rectangle(2, 4);
shapes[3] = new Trapezoid(2, 4, 3);
shapes[4] = new Triangle(3, 4, 5);
double totalArea = 0;
for (int i = 0; i < 5; i++) {
totalArea += shapes[i]->area();
}
cout << "The total area is: " << totalArea << endl;
for (int i = 0; i < 5; i++) {
delete shapes[i];
}
return 0;
}
```
在这个程序中,我们定义了一个抽象类 Shape,它有一个纯虚函数 area()。然后,我们派生出了五个类 Circle、Square、Rectangle、Trapezoid 和 Triangle,它们都重载了 area() 函数,用于计算面积。在 main 函数中,我们创建了一个指针数组 shapes,它的每个元素都指向一个派生类对象。然后,我们用一个循环遍历这个指针数组,计算每个图形的面积并累加到 totalArea 变量中。最后,我们输出 totalArea 变量的值,并释放指针数组中每个元素所指向的对象的内存。
阅读全文