图形的面积与周长计算程序:长方形和圆形都属于几何图形,都有周长和面积,并且它们都有自己的周长和面积计算公式。使用抽象类的知识设计一个程序,可以计算不同图形的面积和周长
时间: 2023-06-18 10:02:41 浏览: 105
好的,我们可以定义一个抽象类 `Shape`,其中包含两个纯虚函数 `get_area()` 和 `get_perimeter()`,用于计算图形的面积和周长。然后我们可以定义两个子类 `Rectangle` 和 `Circle`,它们分别继承自 `Shape`,并实现自己的面积和周长计算方法。
下面是一个示例实现:
```cpp
#include <iostream>
#include <cmath>
using namespace std;
// 抽象类 Shape
class Shape {
public:
// 纯虚函数,用于计算面积和周长
virtual float get_area() = 0;
virtual float get_perimeter() = 0;
};
// 长方形类 Rectangle
class Rectangle : public Shape {
public:
Rectangle(float width, float height) {
this->width = width;
this->height = height;
}
float get_area() {
return width * height;
}
float get_perimeter() {
return 2 * (width + height);
}
private:
float width;
float height;
};
// 圆形类 Circle
class Circle : public Shape {
public:
Circle(float radius) {
this->radius = radius;
}
float get_area() {
return M_PI * radius * radius;
}
float get_perimeter() {
return 2 * M_PI * radius;
}
private:
float radius;
};
int main() {
// 创建一个长方形对象
Rectangle rect(10, 5);
// 计算长方形的面积和周长
cout << "Rectangle area: " << rect.get_area() << endl;
cout << "Rectangle perimeter: " << rect.get_perimeter() << endl;
// 创建一个圆形对象
Circle circle(5);
// 计算圆形的面积和周长
cout << "Circle area: " << circle.get_area() << endl;
cout << "Circle perimeter: " << circle.get_perimeter() << endl;
return 0;
}
```
在这个例子中,我们定义了一个抽象类 `Shape`,然后定义了两个子类 `Rectangle` 和 `Circle`,它们分别实现了 `Shape` 中的纯虚函数。在程序中,我们创建了一个长方形对象和一个圆形对象,然后分别调用它们的 `get_area()` 和 `get_perimeter()` 方法计算它们的面积和周长。