首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

YTUOJ 矩形類設計:運算符重載實現矩形加法與面積輸出

     編輯:關於C++

題目要求

定義 Rectangle 類:

  • 數據成員:左下角 (x1,y1)、右上角 (x2,y2)(double)。
  • 構造函數、輸入函數 input()。
  • 重載 operator+:對應坐標相加(無幾何意義,純數學定義)。
  • 重載 operator<< 輸出面積 (x2-x1)*(y2-y1)。
  • 主函數固定:p1(1,1,6,3)、p2.input()、p3=p1+p2、cout<。

C++ 完整代碼

#include <iostream>
using namespace std;

class Rectangle {
    double x1, y1, x2, y2;
public:
    Rectangle(double a=0, double b=0, double c=0, double d=0)
        : x1(a), y1(b), x2(c), y2(d) {}
    void input() { cin >> x1 >> y1 >> x2 >> y2; }
    friend Rectangle operator+(const Rectangle& a, const Rectangle& b) {
        return Rectangle(a.x1+b.x1, a.y1+b.y1, a.x2+b.x2, a.y2+b.y2);
    }
    friend ostream& operator<<(ostream& out, const Rectangle& r) {
        double area = (r.x2 - r.x1) * (r.y2 - r.y1);
        out << area << endl;
        return out;
    }
};

int main() {
    Rectangle p1(1,1,6,3), p2, p3;
    p2.input();
    p3 = p1 + p2;
    cout << p3;
    return 0;
}

運行示例

輸入:2.5 1.8 4.3 2.5
p2:左下 (2.5,1.8) 右上 (4.3,2.5)
p3:左下 (3.5,2.8) 右上 (10.3,5.5)
面積:(10.3-3.5)*(5.5-2.8) = 6.8*2.7 = 18.36 → 輸出 18.36。

關鍵點

  • 友元函數重載雙目運算符 + 與左移輸出 <<。
  • 構造函數默認參數支持無參構造。
  • 主函數不可修改,類接口需完全匹配。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved