虚函数之定义一个基类Shape,在此基础上派生出Rectangle和Circle再使用Rectangle类创建一个派生类Square。

定义一个基类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;
}
 

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值