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
#include
#include
#define PI 3.14
using namespace std;
class Shape
{
public:
virtual void print()=0;虚函数的使用
};
class Circle:public Shape
{
public:
Circle(double x,double y,double r)
{
this->x=x;
this->y=y;
this->r=r;
}
void print()
{
cout<<fixed<<setprecision(3)<<2
PI*r<<endl;
}
private:
double x;
double y;
double r;

};
class Rectangle:public Shape
{
public:
Rectangle(double x1,double y1,double x2,double y2)
{
this->x1=x1;
this->y1=y1;
this->x2=x2;
this->y2=y2;
}
void print()//不需要加任何参数
{
cout<<fixed<<setprecision(3)<<((x2-x1)*2+(y2-y1)*2)*2<<endl;
}
private:
double x1;
double x2;
double y1;
double y2;
};
int main()
{
double x,y,r,x2,y2,x1,y1;
Shape *p;
while (cin>>x>>y>>r)
{
//p=new Circle(x,y,r);//两种表达方式,这两种方式都可以输出结果
//p->print();
//p=new Rectangle(x1,y1,x2,y2);
// p->print();
Circle s1(x,y,r);
p=&s1;
p->print();
cin>>x1>>y1>>x2>>y2;
Rectangle s2(x1,y1,x2,y2);
p=&s2;
p->print();

 }
return 0;

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值