声明类Shape以及它的3个派生类:Circle、Square、Rectangle,输入半径、边长、长和宽,用虚函数分别计算几种图形的面积、周长,编写程序,建立基类指针数组,每个指针均指向一个派生类对象,利用基类指针 遍历元素对象,求取所有图形面积之和。请绘制UML类图。、
时间: 2023-07-10 20:24:23 浏览: 87
矩形类及派生类,算面积、体积
好的,以下是类的UML类图:
```
+----------------+
| Shape |
+----------------+
| |
| - radius: int |
| - side: int |
| - length: int |
| - width: int |
| |
+----------------+
| |
|+ calcArea(): |
|+ calcPerimeter: |
| |
+----------------+
/ | \
+------------+ +-----------+ +--------------+
| Circle | | Square | | Rectangle |
+------------+ +-----------+ +--------------+
| | | | | |
|+ calcArea()| |+ calcArea()| |+ calcArea() |
|+ calcPeri()| |+ calcPeri()| |+ calcPeri() |
| | | | | |
+------------+ +-----------+ +--------------+
```
下面是这些类的代码实现:
```cpp
#include <iostream>
#include <cmath>
using namespace std;
class Shape {
protected:
int radius;
int side;
int length;
int width;
public:
Shape() {}
virtual ~Shape() {}
virtual double calcArea() = 0;
virtual double calcPerimeter() = 0;
};
class Circle : public Shape {
public:
Circle(int r) : radius(r) {}
virtual ~Circle() {}
virtual double calcArea() override {
return M_PI * radius * radius;
}
virtual double calcPerimeter() override {
return 2 * M_PI * radius;
}
};
class Square : public Shape {
public:
Square(int s) : side(s) {}
virtual ~Square() {}
virtual double calcArea() override {
return side * side;
}
virtual double calcPerimeter() override {
return 4 * side;
}
};
class Rectangle : public Shape {
public:
Rectangle(int l, int w) : length(l), width(w) {}
virtual ~Rectangle() {}
virtual double calcArea() override {
return length * width;
}
virtual double calcPerimeter() override {
return 2 * (length + width);
}
};
int main() {
Shape* shapes[] = {
new Circle(3),
new Rectangle(4, 5),
new Square(2),
new Circle(4),
new Rectangle(2, 6)
};
double total_area = 0.0;
for (int i = 0; i < 5; i++) {
total_area += shapes[i]->calcArea();
}
cout << "Total area: " << total_area << endl;
for (int i = 0; i < 5; i++) {
delete shapes[i];
}
return 0;
}
```
阅读全文