用c++写一个程序,定义抽象基类Shape,由它派生出5个派生类:Circle(圆形)、Square(正方形)、Rectangle(矩形)、Trapezoid(梯形)、Triangle(三角形),用虚函数分别计算几种图形面积,并求它们的和。要 求用基类指针数组,使它的每一个元素指向派生类对象。
时间: 2024-03-24 17:37:06 浏览: 164
调用基类的构造函数-C++程序设计
好的,这是一个关于C++继承和多态的问题。下面是代码实现。
```c++
#include <iostream>
using namespace std;
class Shape {
public:
virtual float area() = 0; // 纯虚函数
};
class Circle : public Shape {
public:
Circle(float r) { radius = r; }
float area() { return 3.14 * radius * radius; }
private:
float radius;
};
class Square : public Shape {
public:
Square(float l) { length = l; }
float area() { return length * length; }
private:
float length;
};
class Rectangle : public Shape {
public:
Rectangle(float w, float h) { width = w; height = h; }
float area() { return width * height; }
private:
float width, height;
};
class Trapezoid : public Shape {
public:
Trapezoid(float a, float b, float h) { top = a; bottom = b; height = h; }
float area() { return (top + bottom) * height / 2; }
private:
float top, bottom, height;
};
class Triangle : public Shape {
public:
Triangle(float b, float h) { base = b; height = h; }
float area() { return base * height / 2; }
private:
float base, height;
};
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(2, 3);
float 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`,并由它派生出5个派生类,每个类实现了自己的`area()`函数来计算面积。在`main()`函数中,定义了一个基类指针数组`shapes`,它的每一个元素指向一个派生类对象。通过循环遍历数组,可以计算出各个图形的面积之和,并输出结果。最后,需要释放内存以避免内存泄漏。
阅读全文