声明类Shape以及它的3个派生类:Circle、Square、Rectangle, 用虚函数分别计算几种图形的面积、周长,编写程序,建立基 类指针数组,每个指针均指向一个派生类对象,利用基类指针 遍历元素对象,求取所有图形面积之和。请绘制UML类图
时间: 2024-02-22 19:55:05 浏览: 102
c++ 形状类Shape(派生出圆类Circle和矩形类Rectangle)
好的,我理解了你的问题。以下是UML类图和相应的C++代码实现。
UML类图:
```
+--------------+
| Shape |
+--------------+
| -name: string|
+--------------+
|+calcArea(): |
|+calcPeri(): |
+--------------+
/_\
|
|
+--------------+
| Circle |
+--------------+
| -radius: double|
+--------------+
|+calcArea(): |
|+calcPeri(): |
+--------------+
/_\
|
|
+--------------+
| Square |
+--------------+
| -side: double|
+--------------+
|+calcArea(): |
|+calcPeri(): |
+--------------+
/_\
|
|
+--------------+
| Rectangle |
+--------------+
| -length: double|
| -width: double|
+--------------+
|+calcArea(): |
|+calcPeri(): |
+--------------+
```
C++代码实现:
```c++
#include<iostream>
#include<string>
using namespace std;
class Shape {
protected:
string name;
public:
Shape(string n) : name(n) {}
virtual double calcArea() = 0;
virtual double calcPeri() = 0;
};
class Circle : public Shape {
private:
double radius;
public:
Circle(string n, double r) : Shape(n), radius(r) {}
double calcArea() { return 3.14 * radius * radius; }
double calcPeri() { return 2 * 3.14 * radius; }
};
class Square : public Shape {
private:
double side;
public:
Square(string n, double s) : Shape(n), side(s) {}
double calcArea() { return side * side; }
double calcPeri() { return 4 * side; }
};
class Rectangle : public Shape {
private:
double length, width;
public:
Rectangle(string n, double l, double w) : Shape(n), length(l), width(w) {}
double calcArea() { return length * width; }
double calcPeri() { return 2 * (length + width); }
};
int main() {
Shape *arr[] = { new Circle("Circle", 5), new Square("Square", 6), new Rectangle("Rectangle", 3, 4) };
double totalArea = 0;
for (int i = 0; i < 3; i++) {
totalArea += arr[i]->calcArea();
}
cout << "Total Area: " << totalArea << endl;
return 0;
}
```
这个程序使用了基类指针数组来指向不同的派生类对象,并使用`calcArea()`函数计算每个图形的面积,最后求取所有图形面积之和。注意:这个程序只是一个示例,实际中可能需要更多的错误检查和数据输入。
阅读全文