请编写一个抽象类Shape,在此基础上派生出类Rectangle和类Circle,二者都有计算对象面积的函数getArea()和计算对象周长的函数getPerim()
为了避免精度问题,这里取圆周率 π=3
#include<bits/stdc++.h>
using namespace std;
//------------------------------code here----------------------------
//-----------------------------------------------------------------------
int main()
{
int x,y,r;
cin>>x>>y>>r;
Shape *shape=new Rectangle(x,y);
cout<<shape->getArea()<<'-'<<shape->getPerim()<<" ";
shape=new Circle(r);
cout<<shape->getArea()<<'-'<<shape->getPerim()<<" ";
}
输入三个数字x,y,r分别代表一个长方形的长和宽,以及圆形的半径
题目已处理,不必实现
样例输入 输出
3 4 5
12-14 75-30
#define PI 3
class Shape {
public:
virtual double getArea() = 0;
virtual double getPerim() = 0;
};
class Rectangle : public Shape {
double length;
double width;
public:
Rectangle() = default;
Rectangle(double l, double w) : length(l), width(w) {}
double getArea() {
return length * width;
}
double getPerim() {
return (length + width) * 2;
}
};
class Circle : public Shape {
double radius;
public:
Circle() = default;
Circle(double r):radius(r){}
double getArea() {
return PI*radius*radius;
}
double getPerim() {
return 2*PI*radius;
}
};