【问题描述】抽象类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
#include <iostream>
#include <cmath>
#define PI 3.14159s
using namespace std;
// 抽象基类 Shape
class Shape {
public:
// 纯虚函数
virtual void print() const = 0;
virtual double getArea() const = 0;
virtual double getPerimeter() const = 0;
// 虚析构函数(可选,但通常用于抽象基类)
virtual ~Shape() {}
};
// Circle 类
class Circle: public Shape {
private:
double radius;
public:
Circle(double r) : radius(r) {}
void print() const {
cout << "Circle: R=" << radius << endl;
}
double getArea() const {
return PI * radius * radius;
}
double getPerimeter() const {
return 2 * PI * radius;
}
};
// Rectangle 类
class Rectangle: public Shape {
private:
double height, width;
public:
Rectangle(double h, double w) : height(h), width(w){}
void print() const {
cout << "Rectangle: Width=" << width << ",Height=" << height << endl;
}
double getArea() const {
return width * height;
}
double getPerimeter() const {
return 2 * (width + height);
}
};
int main() {
Rectangle recA(7.2, 3.5), recB(7.2, 3.5);
Circle circleA(2.3), circleB(1.5);
Shape *pShape[4] = {&recB, &circleA, &circleB, &recA};
for (int i = 0; i < 4; i++) {
pShape[i]->print();
cout << "Area=" << pShape[i]->getArea() << " Perimeter=" << pShape[i]->getPerimeter() << endl;
}
return 0;
}