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()
{
return x * y;
}
Rectangle(){}
};
class Circle :public Shape
{
public:
double R;
Circle(double a)
{
R = a;
}
double getArea()
{
return PI * R * R;
}
Circle(){}
};
class Square :public Rectangle
{
public:
double k;
Square(double a)
{
k = a;
}
double getArea()
{
return k * k;
}
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;
}
#include<iostream>
#include<string.h>
#include<string>
#include<iomanip>
#include<math.h>
using namespace std;
class Shape
{
public:
Shape(){}
virtual double getArea() = 0;
};
class Rectangle :public Shape
{
public:
double c, k;
Rectangle(double a=0, double b=0)
{
c = a; k = b;
}
virtual double getArea()
{
return c * k ;
}
};
class Circle :public Shape
{
public:
double r;
Circle(double a=0.0)
{
r = a;
}
virtual double getArea()
{
return 3.14 * r * r;
}
};
class Square :public Rectangle
{
public:
double bc;
Square(double a)
{
bc = a;
}
virtual double getArea()
{
return bc * bc;
}
};
|