Problem C: 矩形类中运算符重载【C++】
Time Limit: 1 Sec Memory Limit: 128 MBSubmit: 638 Solved: 319
[ Submit][ Status][ Web Board]
Description
定义一个矩形类,数据成员包括左下角和右上角坐标,定义的成员函数包括必要的构造函数、输入坐标的函数,实现矩形加法,以及计算并输出矩形面积的函数。要求使用提示中给出的测试函数并不得改动。
两个矩形相加的规则是:决定矩形的对应坐标分别相加,如
左下角(1,2),右上角(3,4)的矩形,与
左下角(2,3),右上角(4,5)的矩形相加,得到的矩形是
左下角(3,5),右上角(7,9)的矩形。
这个规则没有几何意义,就这么定义好了。
输出面积的功能通过重载"<<"运算完成。
本题可以在2383的基础上扩展完成。
Input
测试函数中第一个矩形直接初始化,第二个矩形通过键盘输入。输入四个数,分别表示第二个矩形左下角和右上角顶点的坐标,如输入2.5 1.8 4.3 2.5,代表左下角坐标为(2.5, 1.8),右上角坐标为(4.3, 2.5)。
Output
输出两点相加后得到的点的面积。运行测试函数时,p1的顶点是1 1 6 3,如果输入的p2是2.5 1.8 4.3 2.5,计算得到的矩形p3的左下角坐标为(3.5, 2.8),右上角坐标为(10.3, 5.5),输出为p3的面积18.36。
Sample Input
2.5 1.8 4.3 2.5
Sample Output
18.36
HINT
int main()
{
Rectangle p1(1,1,6,3),p2,p3;
p2.input();
p3=p1+p2;
cout<<p3;
return 0;
}
提交时请加上主函数。
<span style="font-size:14px;">/*
*Copyright (c)2015,烟台大学计算机与控制工程学院
*All rights reserved.
*作 者:单昕昕
*完成日期:2015年5月16日
*版 本 号:v1.0
*/
#include <iostream>
#include <cmath>
using namespace std;
class Rectangle
{
public:
Rectangle(double x=1.0,double xx=1.0,double y=1.0,double yy=1.0):x1(x),x2(xx),y1(y),y2(yy) {}
void input();
friend ostream& operator<<(ostream&output,const Rectangle &p);
Rectangle operator+(const Rectangle &p);
private:
double x1,x2,y1,y2;
};
void Rectangle::input()
{
double x,xx,y,yy;
cin>>x>>xx>>y>>yy;
x1=x;
x2=xx;
y1=y;
y2=yy;
}
Rectangle Rectangle:: operator+(const Rectangle &p)
{
return Rectangle(x1+p.x1,x2+p.x2,y1+p.y1,y2+p.y2);
}
ostream& operator<<(ostream&output,const Rectangle &p)
{
output<<fabs((p.x1-p.y1)*(p.x2-p.y2));
return output;
}
int main()
{
Rectangle p1(1,1,6,3),p2,p3;
p2.input();
p3=p1+p2;
cout<<p3;
return 0;
}
</span>