定义抽象基类shape,由其派生出5个派生类:circle(圆)、squre(正方形)、Rectangle(长方形)、Triangle(三角形)和Trapeze(梯形),用虚函数分别计算各种图形面积,输出面积和。 要求:用基类指针数据,每一个数组元素指向一个派生类对象
时间: 2024-01-06 07:04:14 浏览: 145
好的,以下是实现上述要求的C++代码:
```cpp
#include <iostream>
using namespace std;
class shape { // 抽象基类
public:
virtual double area() = 0; // 纯虚函数
};
class circle : public shape { // 圆
private:
double r;
public:
circle(double r) { this->r = r; }
double area() { return 3.14 * r * r; }
};
class square : public shape { // 正方形
private:
double a;
public:
square(double a) { this->a = a; }
double area() { return a * a; }
};
class rectangle : public shape { // 长方形
private:
double a, b;
public:
rectangle(double a, double b) { this->a = a; this->b = b; }
double area() { return a * b; }
};
class triangle : public shape { // 三角形
private:
double a, h;
public:
triangle(double a, double h) { this->a = a; this->h = h; }
double area() { return 0.5 * a * h; }
};
class trapeze : public shape { // 梯形
private:
double a, b, h;
public:
trapeze(double a, double b, double h) { this->a = a; this->b = b; this->h = h; }
double area() { return (a + b) * h / 2; }
};
int main() {
shape* s[5]; // 基类指针数组
s[0] = new circle(2);
s[1] = new square(3);
s[2] = new rectangle(2, 4);
s[3] = new triangle(2, 3);
s[4] = new trapeze(2, 4, 3);
double sum = 0;
for (int i = 0; i < 5; i++) {
sum += s[i]->area();
cout << "第" << i + 1 << "个图形的面积为:" << s[i]->area() << endl;
}
cout << "总面积为:" << sum << endl;
for (int i = 0; i < 5; i++) {
delete s[i]; // 释放内存
}
return 0;
}
```
程序输出为:
```
第1个图形的面积为:12.56
第2个图形的面积为:9
第3个图形的面积为:8
第4个图形的面积为:3
第5个图形的面积为:9
总面积为:41.56
```
程序中,通过抽象基类`shape`定义了一个纯虚函数`area()`,并由其派生出了五个派生类`circle`、`square`、`rectangle`、`triangle`和`trapeze`,分别计算出各自的面积。通过基类指针数组`s`,每一个数组元素指向一个派生类对象,实现了多态的调用。最后输出每个图形的面积和总面积,并释放内存。
阅读全文