定义一个基类Shape,在此基础上派生出Rectangle和Circle,二者都有getArea( )函数计算对象的面积,再使用Rectangle类创建一个派生类Square。将getArea()改造为虚函数。在主函数当中,只使用一个Shape *类型的指针p,依次指向Rectangle、Circle和Square的一个对象,并通过p->getArea()计算面积。
输入格式
Rectangle的长和宽、Circle的半径、Square的边长
输出格式
对应的面积,四舍五入到整数
输入样例
3 7 6 4
2.1 3.5 10.3 4.5
输出样例
21 113 16
7 333 20
示例:
#include <iostream>
#include <math.h>
using namespace std;
float pi = 3.1415926;
class Shape
{
protected:
float x, y;
//在矩形中x.y表示为长和宽,在圆形中都表示为半径,在正方形中都表示为边长
public:
void getxy(float X, float Y);
virtual void getArea();//虚函数
};
void Shape::getxy(float X, float Y) { x = X; y = Y; }
void Shape::getArea() { cout << round(x * y) << endl; }
//派生Rectangle
class Rectangle : public Shape
{
public:
void getlw(float l, float w);//读取长度和宽度
};
void Rectangle::getlw(float l, float w) { x = l; y = w; }
//派生Circle
class Circle : public Shape
{
public:
void getr(float r);//读取半径
virtual void getArea();
};
void Circle::getr(float r) { x = r; y = r; }
void Circle::getArea() { cout << round( pi* x * y) << endl; }//圆的面积输出
class Square : public Rectangle
{
public:
void getb(float b);//读取边长
};
void Square::getb(float b) { x = b; y = b; }
void fun(Shape* p)//定义函数参数为指向基类对象的指针
{
p->getArea();
}
int main()
{
Rectangle myjx;
Circle myyx;
Square myzfx;
float x, y, r, b;
while (cin >> x >> y >> r >> b)
{
myjx.getxy(x, y);
fun(&myjx);
myyx.getr(r);
fun(&myyx);
myzfx.getb(b);
fun(&myzfx);
}
return 0;
}