Problem Description
定义一个图形基类Shape,在此基础上派生出长方形Rectangle和圆Circle,
使用Rectangle类派生正方形类Square。计算图形的面积。
请完善下面的程序。
//你的代码将被嵌在这里
int main()
{
Shape* ps;
Rectangle* pr;
double r;
cin >> r;
ps = new Circle(r);
cout << "The area of the Circle is " << ps->getArea() << endl;
delete ps;
double l,w;
cin >> l>>w;
ps = new Rectangle(l, w);
cout << "The area of the Rectagle is " << ps->getArea() << endl;
delete ps;
double s1;
cin >> s1;
ps = new Square(s1);
cout << "The area of the Square is " << ps->getArea() << endl;
delete ps;
double s2;
cin >> s2;
pr = new Square(s2);
cout << "The area of the Square is " << pr->getArea() << endl;
delete pr;
return 0;
}
Input Description
第1个数是圆的半径
第2、3个数是长方形的长和宽
第4个数是一个正方形的边长
第5个数是另一个正方形的边长
Sample Input
1 2 3 4 5
Sample Output
The area of the Circle is 3.14
The area of the Rectagle is 6
The area of the Square is 16
The area of the Square is 25
#include <iostream>
using namespace std;
constexpr double PI = 3.14;
class Shape
{
public:
Shape(){
}//基类要有构造函数
virtual double getArea() = 0;//纯虚函数
};
class Rectangle:public Shape
{
public:
double x, y;
Rectangle(double a, double b)
{
x = a;
y = b;
}
double getArea

该博客介绍了一个C++编程任务,涉及创建一个图形基类Shape,以及Rectangle(长方形)、Circle(圆)和Square(正方形)的派生类。通过这些类,程序可以计算并输出不同图形的面积。示例输入包括圆的半径和不同正方形、长方形的尺寸,输出为对应图形的面积。
1371

被折叠的 条评论
为什么被折叠?



