写一个程序,定义抽象基类Shape,由它派生出5个派生类:Circle、Square、Rectangle、Tarpezoid、Triangle。用虚函数分别计算几种图形面积,并求它们的和。要求用基类指针数组,使它的每一个元素指向一个派生类对象。
时间: 2025-06-09 22:02:47 浏览: 12
首先,我们可以定义一个抽象基类`Shape`,包含一个纯虚函数`getArea()`用于计算面积。然后,我们创建五个派生类:`Circle`、`Square`、`Rectangle`、`Trapezoid`和`Triangle`,每个类都会实现自己的`getArea()`方法。
```cpp
#include <iostream>
class Shape {
public:
virtual double getArea() const = 0; // 纯虚函数,声明但不提供实现
};
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) : radius(r) {}
double getArea() const override { return M_PI * radius * radius; }
};
class Square : public Shape {
private:
double side;
public:
Square(double s) : side(s) {}
double getArea() const override { return side * side; }
};
class Rectangle : public Shape {
private:
double length, width;
public:
Rectangle(double l, double w) : length(l), width(w) {}
double getArea() const override { return length * width; }
};
class Trapezoid : public Shape {
private:
double base1, base2, height;
public:
Trapezoid(double b1, double b2, double h) : base1(b1), base2(b2), height(h) {}
double getArea() const override { return (base1 + base2) / 2 * height; }
};
class Triangle : public Shape {
private:
double a, b, c; // 假设使用海伦公式计算面积
public:
Triangle(double a, double b, double c) : a(a), b(b), c(c) {}
double getArea() const override {
double s = (a + b + c) / 2;
return sqrt(s * (s - a) * (s - b) * (s - c));
}
};
int main() {
Shape* shapes[5] = {
new Circle(5),
new Square(4),
new Rectangle(6, 8),
new Trapezoid(3, 7, 4),
new Triangle(3, 4, 5)
};
double totalArea = 0;
for (Shape* shape : shapes) {
totalArea += shape->getArea();
delete shape; // 注意内存管理
}
std::cout << "Total area of all shapes: " << totalArea << std::endl;
return 0;
}
```
在这个例子中,我们用一个基类指针数组存储了各种形状的对象,通过调用`getArea()`虚函数来计算它们各自的面积并求和。注意在实际编程中,需要处理好动态分配的内存,如上述代码中的`delete shape`部分。
阅读全文
相关推荐

















