1063: C++:多态性1(动态联编测试)

题目描述
有一个名为Shape的基类,它有2个派生类:Circle(圆)和Rectangle(长方形)。测试程序如下:

int main()
{ double x,y,r,x2,y2;
Shape *p;
while (cin>>x>>y>>r)
{ p=new Circle(x,y,r); p->print();
cin>>x>>y>>x2>>y2; p=new Rectangle(x,y,x2,y2); p->print();
}
}

要求:

(1)完成以下功能:对给出的圆心坐标与半径,求圆的周长; 对给出的长方形中心坐标和一个顶点坐标,求长方形的周长。

(2)设计3个类。在Shape中定义虚函数print,在 Circle和Rectangle中重载该函数计算并显示周长。

输入
包含多组测试例, 每组数据的第1行是圆心的坐标和半径,第2行是长方形的中心坐标和一个顶点坐标。
输出
圆的周长和长方形的周长(保留3位小数)。
样例输入 Copy
2 3.5 12.3
0 0 2.3 2.3
5 5 5.8
2 2 5.6 5.6
样例输出 Copy
77.244
18.400
36.424
28.800
提示
#define PI 3.14

# include <iostream>
using namespace std;
# include <iomanip>
# include <cmath>

class Shape
{
public:
    virtual void print() {}
    Shape(double x_, double y_)
    {
        x = x_;
        y = y_;
    }

    double getX()
    {
        return x;
    }

    double getY()
    {
        return y;
    }

private:
    double x, y;
};

class Circle :public Shape
{
public:
    Circle(double x_, double y_, double r_):Shape(x_, y_), r(r_){}
    void print()
    {
        cout << fixed << setprecision(3) << 2 * 3.14 * r << endl;
    }

private:
    double r;

};

class Rectangle :public Shape
{
public:
    Rectangle(double x_, double y_, double x1_, double y1_):Shape(x_, y_), x1(x1_), y1(y1_){}
    void print()
    {
        cout << fixed << setprecision(3) << 4 * (fabs(x1 - getX()) + fabs(y1 - getY())) << endl;
    }
private:
    double x1, y1;
};

int main()
{
    double x, y, r, x2, y2;
    Shape* p;
    while (cin >> x >> y >> r)
    {
        p = new Circle(x, y, r);  p->print();
        cin >> x >> y >> x2 >> y2;  p = new Rectangle(x, y, x2, y2);  p->print();
        delete[] p;//原程序中没有
    }
    
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值