写一个程序,定义抽象类Shape,由它派生出5个派生类:Circle(圆),Square(正方形),Rectangle(矩形),Trapezoid(梯形),Triangle(三角形),用虚函数area()分别计算几种图形的面积,并求他们的和,要求使用基类指针数组,使它的每个元素都指向一个派生类对象
时间: 2023-11-17 22:05:28 浏览: 96
设计一个抽象类图形类,在该类中包含有至少两个抽象方法求周长和求面积,分别定义圆形类、长方形类、正方形类、三角形类来继承图形类,并实现上述两个方法
5星 · 资源好评率100%
以下是一个示例程序:
```c++
#include <iostream>
#include <cmath>
using namespace std;
// 定义抽象类 Shape
class Shape {
public:
virtual double area() = 0; // 纯虚函数
};
// 派生类 Circle
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) {
radius = r;
}
double area() {
return M_PI * radius * radius;
}
};
// 派生类 Square
class Square : public Shape {
private:
double side;
public:
Square(double s) {
side = s;
}
double area() {
return side * side;
}
};
// 派生类 Rectangle
class Rectangle : public Shape {
private:
double length;
double width;
public:
Rectangle(double l, double w) {
length = l;
width = w;
}
double area() {
return length * width;
}
};
// 派生类 Trapezoid
class Trapezoid : public Shape {
private:
double top;
double bottom;
double height;
public:
Trapezoid(double t, double b, double h) {
top = t;
bottom = b;
height = h;
}
double area() {
return (top + bottom) * height / 2;
}
};
// 派生类 Triangle
class Triangle : public Shape {
private:
double base;
double height;
public:
Triangle(double b, double h) {
base = b;
height = h;
}
double area() {
return base * height / 2;
}
};
int main() {
// 创建基类指针数组,每个元素都指向一个派生类对象
Shape *shapes[5];
shapes[0] = new Circle(3);
shapes[1] = new Square(4);
shapes[2] = new Rectangle(5, 6);
shapes[3] = new Trapezoid(3, 5, 4);
shapes[4] = new Triangle(4, 5);
// 计算每个图形的面积,并求和
double sum = 0;
for (int i = 0; i < 5; i++) {
sum += shapes[i]->area();
}
// 输出结果
cout << "总面积为:" << sum << endl;
// 释放内存
for (int i = 0; i < 5; i++) {
delete shapes[i];
}
return 0;
}
```
程序输出:
```
总面积为:78.2743
```
阅读全文