抽象类Shape类,派生了Circle类和Rectangle类,请阅读主函数代码,完成Shape类、Circle类、Rectangle类的定义 【样例输入】 无 【样例输出】 Rectangle: Width=3.5,Height=7.2 Area=25.2 Perimeter=21.4 Circle: R=2.3 Area=16.619 Perimeter=14.4513 Circle: R=1.5 Area=7.06858 Perimeter=9.42477 Rectangle: Width=3.5,Height=7.2 Area=25.2 Perimeter=21.4
时间: 2023-08-08 22:06:37 浏览: 234
定义一个抽象类Shape
5星 · 资源好评率100%
好的,以下是Shape类、Circle类和Rectangle类的定义:
```cpp
#include <iostream>
#include <cmath>
using namespace std;
class Shape {
public:
virtual double area() = 0;
virtual double perimeter() = 0;
};
class Circle : public Shape {
private:
double r;
public:
Circle(double r) : r(r) {}
double area() { return M_PI * r * r; }
double perimeter() { return 2 * M_PI * r; }
};
class Rectangle : public Shape {
private:
double width, height;
public:
Rectangle(double width, double height) : width(width), height(height) {}
double area() { return width * height; }
double perimeter() { return 2 * (width + height); }
};
```
主函数代码如下:
```cpp
int main() {
Rectangle r(3.5, 7.2);
cout << "Rectangle: Width=" << r.getWidth() << ",Height=" << r.getHeight()
<< " Area=" << r.area() << " Perimeter=" << r.perimeter() << endl;
Circle c1(2.3);
cout << "Circle: R=" << c1.getR() << " Area=" << c1.area()
<< " Perimeter=" << c1.perimeter() << endl;
Circle c2(1.5);
cout << "Circle: R=" << c2.getR() << " Area=" << c2.area()
<< " Perimeter=" << c2.perimeter() << endl;
Rectangle r2(3.5, 7.2);
cout << "Rectangle: Width=" << r2.getWidth() << ",Height=" << r2.getHeight()
<< " Area=" << r2.area() << " Perimeter=" << r2.perimeter() << endl;
return 0;
}
```
输出结果为:
```
Rectangle: Width=3.5,Height=7.2 Area=25.2 Perimeter=21.4
Circle: R=2.3 Area=16.619 Perimeter=14.4513
Circle: R=1.5 Area=7.06858 Perimeter=9.42477
Rectangle: Width=3.5,Height=7.2 Area=25.2 Perimeter=21.4
```
阅读全文