已知抽象类类Shape定义如下,其中两个纯虚函数分别为计算面积getArea()和计算周长getPerim()。请通过Shape类派生出矩形类Rectangle和圆类Circle,计算各自的面积和周长,并能够按照main函数给出的测试代码完成给定的输入。 ####Shape类定义及测试程序如下: #include <iostream> using namespace std; const double PI=3.14; class Shape { public: virtual double getArea()=0; virtual double getPerim()=0; }; /*请在这里输入你的代码*/ int main(){ double r,l,w; cin>>r; cin>>l>>w; Shape *p=NULL; p=new Circle(r); print(p);//输出圆面积与周长 p=new Rectangle(l,w); print(p);//输出矩形面积与周长 return 0; } 输入样例: 1 2 3 输出样例: Area:3.14 Perimeter:6.28 Area:6 Perimeter:10
时间: 2024-02-29 22:52:24 浏览: 85
请参考以下代码:
```c++
#include <iostream>
using namespace std;
const double PI=3.14;
class Shape {
public:
virtual double getArea()=0;
virtual double getPerim()=0;
};
class Circle : public Shape {
private:
double r;
public:
Circle(double r) : r(r) {}
double getArea() { return PI * r * r; }
double getPerim() { return 2 * PI * r; }
};
class Rectangle : public Shape {
private:
double l, w;
public:
Rectangle(double l, double w) : l(l), w(w) {}
double getArea() { return l * w; }
double getPerim() { return 2 * (l + w); }
};
void print(Shape *p) {
cout << "Area:" << p->getArea() << " ";
cout << "Perimeter:" << p->getPerim() << endl;
}
int main() {
double r, l, w;
cin >> r;
cin >> l >> w;
Shape *p = NULL;
p = new Circle(r);
print(p);
p = new Rectangle(l, w);
print(p);
return 0;
}
```
运行结果:
输入:
1 2 3
输出:
Area:3.14 Perimeter:6.28
Area:6 Perimeter:10
阅读全文