#include <iostream>
#include <cmath>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
// 定义抽象类Shape
class Shape {
public:
virtual double area() = 0; // 纯虚函数
};
// 长方形类
class Rectangle : public Shape {
private:
double width, height;
public:
Rectangle(double w, double h) : width(w), height(h) {}
double area() override {
return width * height;
}
};
// 梯形类
class Trapezoid : public Shape {
private:
double base1, base2, height;
public:
Trapezoid(double b1, double b2, double h) : base1(b1), base2(b2), height(h) {}
double area() override {
return (base1 + base2) * height / 2.0;
}
};
// 圆形类
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) : radius(r) {}
double area() override {
return M_PI * pow(radius, 2);
}
};
int main() {
Shape* shapes[3];
shapes[0] = new Rectangle(5.0, 4.0);
shapes[1] = new Trapezoid(2.0, 3.0, 4.0);
shapes[2] = new Circle(3.0);
for(int i = 0; i < 3; i++) {
std::cout << "Shape " << i+1 << " area: " << shapes[i]->area() << std::endl;
delete shapes[i];
}
return 0;
}