• 问题 B: 矩形类中运算符重载【C++】


    题目描述

      定义一个矩形类,数据成员包括左下角和右上角坐标,定义的成员函数包括必要的构造函数、输入坐标的函数,实现矩形加法,以及计算并输出矩形面积的函数。要求使用提示中给出的测试函数并不得改动。
      两个矩形相加的规则是:决定矩形的对应坐标分别相加,如
        左下角(1,2),右上角(3,4)的矩形,与
        左下角(2,3),右上角(4,5)的矩形相加,得到的矩形是
        左下角(3,5),右上角(7,9)的矩形。
      这个规则没有几何意义,就这么定义好了。
      输出面积的功能通过重载"<<"运算完成。
      本题可以在2383的基础上扩展完成。

    输入

    测试函数中第一个矩形直接初始化,第二个矩形通过键盘输入。输入四个数,分别表示第二个矩形左下角和右上角顶点的坐标,如输入2.5 1.8 4.3 2.5,代表左下角坐标为(2.5, 1.8),右上角坐标为(4.3, 2.5)。

    输出

    输出两点相加后得到的点的面积。运行测试函数时,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。

    样例输入

    2.5 1.8 4.3 2.5
    

    样例输出

    18.36

    提示

    int main()

    {

        Rectangle p1(1,1,6,3),p2,p3;

        p2.input();

        p3=p1+p2;

        cout<<p3;

        return 0;

    }


    提交时请加上主函数。

     
    #include <iostream>
    using namespace std;
    
    class Rectangle
    {
    	private :
    		double x1, y1, x2, y2;
    	
    	public :
    		Rectangle();
    		Rectangle(double x1, double y1, double x2, double y2);
    		
    		void input();
    		friend Rectangle operator + (Rectangle &r1, Rectangle &r2);
    		friend ostream & operator << (ostream &output, Rectangle &T);
    };
    
    Rectangle::Rectangle() {
    	
    }
    
    Rectangle::Rectangle(double x1, double y1, double x2, double y2) {
    	
    	this->x1 = x1;
    	this->y1 = y1;
    	this->x2 = x2;
    	this->y2 = y2;
    }
    
    void Rectangle::input() {
    	
    	cin >> x1 >> y1 >> x2 >> y2;
    	
    	return ;
    }
    
    Rectangle operator + (Rectangle &r1, Rectangle &r2)
    {
    	return Rectangle(r1.x1 + r2.x1, r1.y1 + r2.y1, r1.x2 + r2.x2,  r1.y2 + r2.y2);
    }
    
    ostream & operator << (ostream &output, Rectangle &r) {
    	
    	double c;
    	c = (r.x2 - r.x1) * (r.y2 - r.y1);
    	output << c;
    	
    	return output;
    }
    
    int main()
    
     {
    
         Rectangle p1(1,1,6,3),p2,p3;
    
         p2.input();
    
         p3=p1+p2;
    
         cout<<p3;
    
         return 0;
    
     }
    

      

  • 相关阅读:
    Git远程仓库的使用(github为例)
    SQL查看数据库中每张表的数据量和总数据量
    HTML简单的注册页面搭建
    java新建日期获取工具
    ArrayList的使用方法技巧(转载)
    UI初级 TextField
    UI初级 Label
    UI入门 纯代码 第一节 UIWindow, UIView
    C 入门 第十一节
    secoclient安装mac版提示系统配置文件写入失败的解决方案
  • 原文地址:https://www.cnblogs.com/mjn1/p/10648108.html
Copyright © 2020-2023  润新知