18周 oj 矩形类中运算符重载

来源:互联网 发布:ally mac tyana磁力 编辑:程序博客网 时间:2024/06/05 05:38
/*定义一个矩形类,数据成员包括左下角和右上角坐标,定义的成员函数包括必要的构造函数、输入坐标的函数,实现矩形加法,以及计算并输出矩形面积的函数。要求使用提示中给出的测试函数并不得改动。  两个矩形相加的规则是:决定矩形的对应坐标分别相加,如    左下角(1,2),右上角(3,4)的矩形,与    左下角(2,3),右上角(4,5)的矩形相加,得到的矩形是    左下角(3,5),右上角(7,9)的矩形。  这个规则没有几何意义,就这么定义好了。  输出面积的功能通过重载"<<"运算完成。*/#include <iostream>using namespace std;class Rectangle{public:    Rectangle()    {        x1=0;        y1=0;        x2=0;        y2=0;    }    Rectangle(double a,double b,double c,double d) :x1(a),y1(b),x2(c),y2(d){}    Rectangle operator + (Rectangle &p);    friend ostream&operator << (ostream &,Rectangle &);    void input();private:    double x1,y1,x2,y2;};void Rectangle::input(){    cin>>x1>>y1>>x2>>y2;}Rectangle Rectangle::operator + (Rectangle &p){    Rectangle r;    r.x1=x1+p.x1;    r.y1=y1+p.y1;    r.x2=x2+p.x2;    r.y2=y2+p.y2;    return r;}ostream&operator << (ostream &output,Rectangle &r){    output<<(r.x2-r.x1)*(r.y2-r.y1);    return output;}int main(){    Rectangle p1(1,1,6,3),p2,p3;    p2.input();    p3=p1+p2;    cout<<p3;    return 0;}

0 0
原创粉丝点击