【OJ】(二)---B---矩形类中运算符重载

来源:互联网 发布:ncut算法matlab 编辑:程序博客网 时间:2024/06/04 18:16


题目要求如下:

-----------------------------------------------------------------------------------------------------------------------------------------------

代码如下:

/* * Copyright (c) 2013, 烟台大学计算机学院 * All rights reserved. * 作    者:  沈远宏 * 完成日期:2014 年 06月27日 * 版 本 号:v1.0 * 问题描述: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。*/#include <iostream>using namespace std;class Point{private:    double x;    double y;public:    Point(double xx=0,double yy=0):x(xx),y(yy) {}    void set(double xx,double yy)    {        x=xx;        y=yy;    }    double get_x()    {        return x;    }    double get_y()    {        return y;    }};class Rectangle{private:    Point p1;    Point p2;public:    Rectangle(double x1=0,double y1=0,double x2=0,double y2=0)    {        p1.set(x1,y1);        p2.set(x2,y2);    }    Rectangle(Rectangle &r);    void input();    void output();    double R_area();    friend Rectangle operator +(Rectangle r1,Rectangle r2);    friend ostream& operator <<(ostream&,Rectangle r);};Rectangle::Rectangle(Rectangle &r){    p1.set(r.p1.get_x(),r.p1.get_y());    p2.set(r.p2.get_x(),r.p2.get_y());}void Rectangle::input(){    double x1,y1,x2,y2;    cin>>x1>>y1>>x2>>y2;    p1.set(x1,y1);    p2.set(x2,y2);}void Rectangle::output(){    cout<<R_area()<<endl;}double Rectangle::R_area(){    return (p2.get_x()-p1.get_x())*(p2.get_y()-p1.get_y());}Rectangle operator +(Rectangle r1,Rectangle r2){    Rectangle r;    r.p1.set(r1.p1.get_x()+r2.p1.get_x(),r1.p1.get_y()+r2.p1.get_y());    r.p2.set(r1.p2.get_x()+r2.p2.get_x(),r1.p2.get_y()+r2.p2.get_y());    return r;}ostream& operator <<(ostream& cout,Rectangle r){    cout<<r.R_area()<<endl;    return cout;}int main(){    Rectangle p1(1,1,6,3),p2,p3;    p2.input();    p3=p1+p2;    cout<<p3;    return 0;}

运行结果:


OJ要求结果输出例样:


0 0