设计一个Shape(形状)基类,具有calculateArea()(计算面积)的纯虚函数。从Shape 类派生出Rectangle(矩形)和Circle(圆)类,并实现对应的计算面积函数。然后创建对象并打印 其面积。
时间: 2024-02-04 08:04:00 浏览: 93
c++ 形状类Shape(派生出圆类Circle和矩形类Rectangle)
好的,我来模拟一下这个过程。
首先,我们定义一个Shape基类,它有一个纯虚函数calculateArea(),用于计算形状的面积:
```cpp
class Shape {
public:
virtual double calculateArea() = 0;
};
```
接下来,我们从Shape类派生出Rectangle类和Circle类,并实现它们的计算面积函数:
```cpp
class Rectangle : public Shape {
public:
Rectangle(double w, double h) : width(w), height(h) {}
double calculateArea() override { return width * height; }
private:
double width;
double height;
};
class Circle : public Shape {
public:
Circle(double r) : radius(r) {}
double calculateArea() override { return 3.1415926 * radius * radius; }
private:
double radius;
};
```
现在我们可以创建Rectangle和Circle对象,并打印它们的面积了:
```cpp
#include <iostream>
int main() {
Shape* shape1 = new Rectangle(3, 4);
Shape* shape2 = new Circle(5);
std::cout << "Rectangle area: " << shape1->calculateArea() << std::endl;
std::cout << "Circle area: " << shape2->calculateArea() << std::endl;
delete shape1;
delete shape2;
return 0;
}
```
输出结果为:
```
Rectangle area: 12
Circle area: 78.5398
```
这样我们就完成了这个问题的模拟,希望能够帮到你!
阅读全文