设计一个图形类(Shape),由它派生出5个派生类:三角形类(Triangle)、正方形类(Square)、圆形类(Circle)、矩形类(Rectangle)、梯形类(triangle)类,利用虚函数计算图形面积,用一个函数printArea分别输出以上5者的面积。
时间: 2023-12-30 17:02:34 浏览: 67
好的,以下是实现该题目的 C++ 代码:
```cpp
#include<iostream>
using namespace std;
class Shape { // 基类 Shape
public:
virtual double getArea() { return 0; } // 定义虚函数计算面积
};
class Triangle : public Shape { // 三角形类
private:
double base;
double height;
public:
Triangle(double b, double h) : base(b), height(h) {}
virtual double getArea() { return 0.5 * base * height; }
};
class Square : public Shape { // 正方形类
private:
double side;
public:
Square(double s) : side(s) {}
virtual double getArea() { return side * side; }
};
class Circle : public Shape { // 圆形类
private:
double radius;
public:
Circle(double r) : radius(r) {}
virtual double getArea() { return 3.14 * radius * radius; }
};
class Rectangle : public Shape { // 矩形类
private:
double length;
double width;
public:
Rectangle(double l, double w) : length(l), width(w) {}
virtual double getArea() { return length * width; }
};
class Trapezoid : public Shape { // 梯形类
private:
double upperBase;
double lowerBase;
double height;
public:
Trapezoid(double ub, double lb, double h) : upperBase(ub), lowerBase(lb), height(h) {}
virtual double getArea() { return (upperBase + lowerBase) * height / 2; }
};
void printArea(Shape* shape) { // 输出各个图形的面积
if (Triangle* t = dynamic_cast<Triangle*>(shape)) {
cout << "Triangle area: " << t->getArea() << endl;
} else if (Square* s = dynamic_cast<Square*>(shape)) {
cout << "Square area: " << s->getArea() << endl;
} else if (Circle* c = dynamic_cast<Circle*>(shape)) {
cout << "Circle area: " << c->getArea() << endl;
} else if (Rectangle* r = dynamic_cast<Rectangle*>(shape)) {
cout << "Rectangle area: " << r->getArea() << endl;
} else if (Trapezoid* tp = dynamic_cast<Trapezoid*>(shape)) {
cout << "Trapezoid area: " << tp->getArea() << endl;
} else {
cout << "Unknown shape!" << endl;
}
}
int main() {
Shape* shapes[5];
shapes[0] = new Triangle(5, 6);
shapes[1] = new Square(4);
shapes[2] = new Circle(3);
shapes[3] = new Rectangle(7, 8);
shapes[4] = new Trapezoid(4, 6, 5);
for (int i = 0; i < 5; i++) {
printArea(shapes[i]);
}
return 0;
}
```
程序的输出结果为:
```
Triangle area: 15
Square area: 16
Circle area: 28.26
Rectangle area: 56
Trapezoid area: 25
```
阅读全文