[YTU]_2384( 矩形类中运算符重载【C++】)
生活随笔
收集整理的這篇文章主要介紹了
[YTU]_2384( 矩形类中运算符重载【C++】)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
定義一個矩形類,數(shù)據(jù)成員包括左下角和右上角坐標,定義的成員函數(shù)包括必要的構(gòu)造函數(shù)、輸入坐標的函數(shù),實現(xiàn)矩形加法,以及計算并輸出矩形面積的函數(shù)。要求使用提示中給出的測試函數(shù)并不得改動。兩個矩形相加的規(guī)則是:決定矩形的對應(yīng)坐標分別相加,如左下角(1,2),右上角(3,4)的矩形,與左下角(2,3),右上角(4,5)的矩形相加,得到的矩形是左下角(3,5),右上角(7,9)的矩形。這個規(guī)則沒有幾何意義,就這么定義好了。輸出面積的功能通過重載"<<"運算完成。本題可以在2383的基礎(chǔ)上擴展完成。
輸入
測試函數(shù)中第一個矩形直接初始化,第二個矩形通過鍵盤輸入。輸入四個數(shù),分別表示第二個矩形左下角和右上角頂點的坐標,如輸入2.5 1.8 4.3 2.5,代表左下角坐標為(2.5, 1.8),右上角坐標為(4.3, 2.5)。
輸出
輸出兩點相加后得到的點的面積。運行測試函數(shù)時,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
提示
#include <iostream> using namespace std; class Rectangle { public:Rectangle();Rectangle(double x11,double y11,double x22,double y22):x1(x11),y1(y11),x2(x22),y2(y22){}void input();Rectangle operator+(Rectangle &); // friend istream&operator>>(istream &cin,Rectangle &);friend ostream& operator <<(ostream &cout,Rectangle &); private:double x1,y1,x2,y2; }; Rectangle::Rectangle(){} void Rectangle::input() {cin>>x1>>y1>>x2>>y2; } Rectangle Rectangle:: operator+(Rectangle &p) {return Rectangle(x1+p.x1,y1+p.y1,x2+p.x2,y2+p.y2);} ostream& operator<<(ostream &cout,Rectangle &p) {cout<<(p.x2-p.x1)*(p.y2-p.y1)<<endl;return cout; } 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 { public:Rectangle();Rectangle(double x11,double y11,double x22,double y22):x1(x11),y1(y11),x2(x22),y2(y22){}void input();Rectangle operator+(Rectangle &); // friend istream&operator>>(istream &cin,Rectangle &);friend ostream& operator <<(ostream &cout,Rectangle &); private:double x1,y1,x2,y2; }; Rectangle::Rectangle(){} void Rectangle::input() {cin>>x1>>y1>>x2>>y2; } Rectangle Rectangle:: operator+(Rectangle &p) {return Rectangle(x1+p.x1,y1+p.y1,x2+p.x2,y2+p.y2);} ostream& operator<<(ostream &cout,Rectangle &p) {cout<<(p.x2-p.x1)*(p.y2-p.y1)<<endl;return cout; } int main() {Rectangle p1(1,1,6,3),p2,p3;p2.input();p3=p1+p2;cout<<p3;return 0; }
總結(jié)
以上是生活随笔為你收集整理的[YTU]_2384( 矩形类中运算符重载【C++】)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [YTU]_2535 (Problem
- 下一篇: [YTU]_2907( 类重载实现矩阵加