声明类Shape以及它的3个派生类:Circle、Square、Rectangle, 用虚函数分别计算几种图形的面积、周长,编写程序,建立基 类指针数组,每个指针均指向一个派生类对象,利用基类指针 遍历元素对象,求取所有图形面积之和。请绘制UML类图。
时间: 2024-02-22 12:59:54 浏览: 29
好的,我知道你的问题了。以下是 UML 类图以及代码实现:
UML 类图:
```
+----------------+ +---------+
| Shape |<------| Circle |
+----------------+ +---------+
| +calcArea() | | |
|+calcPerimeter()| | |
+----------------+ +---------+
^
|
+----------------+ +---------+
| Square |<------| Rectangle|
+----------------+ +---------+
| +calcArea() | | |
|+calcPerimeter()| | |
+----------------+ +---------+
```
C++ 代码实现:
```cpp
#include <iostream>
#include <vector>
using namespace std;
class Shape
{
public:
virtual double calcArea() = 0;
virtual double calcPerimeter() = 0;
};
class Circle : public Shape
{
public:
Circle(double r) : radius(r) {}
double calcArea() { return 3.14 * radius * radius; }
double calcPerimeter() { return 2 * 3.14 * radius; }
private:
double radius;
};
class Square : public Shape
{
public:
Square(double l) : length(l) {}
double calcArea() { return length * length; }
double calcPerimeter() { return 4 * length; }
private:
double length;
};
class Rectangle : public Shape
{
public:
Rectangle(double l, double w) : length(l), width(w) {}
double calcArea() { return length * width; }
double calcPerimeter() { return 2 * (length + width); }
private:
double length;
double width;
};
int main()
{
vector<Shape*> shapes;
shapes.push_back(new Circle(5));
shapes.push_back(new Square(4));
shapes.push_back(new Rectangle(5, 3));
double totalArea = 0;
for (int i = 0; i < shapes.size(); i++)
{
totalArea += shapes[i]->calcArea();
}
cout << "Total area: " << totalArea << endl;
return 0;
}
```
请注意,Shape 类是一个抽象类,因此它的 calcArea() 和 calcPerimeter() 函数都是纯虚函数,没有实现。Circle、Square 和 Rectangle 类都继承自 Shape 类,并实现了 calcArea() 和 calcPerimeter() 函数。
在主函数中,我们创建了一个 Shape* 类型的 vector,并向其中添加了 Circle、Square 和 Rectangle 对象。然后,我们遍历 vector 中的对象,并计算它们的面积之和。最后,我们输出总面积。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)