問題 B: 矩形類中運算符重載【C++】
阿新 • • 發佈:2019-04-03
個數 決定 ble include urn ont tor 運算符 函數
題目描述
定義一個矩形類,數據成員包括左下角和右上角坐標,定義的成員函數包括必要的構造函數、輸入坐標的函數,實現矩形加法,以及計算並輸出矩形面積的函數。要求使用提示中給出的測試函數並不得改動。
兩個矩形相加的規則是:決定矩形的對應坐標分別相加,如
左下角(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; }
問題 B: 矩形類中運算符重載【C++】