定義 Rectangle 類:
(x1,y1)、右上角 (x2,y2)(double)。input()。operator+:對應坐標相加(無幾何意義,純數學定義)。operator<< 輸出面積 (x2-x1)*(y2-y1)。p1(1,1,6,3)、p2.input()、p3=p1+p2、cout<。 #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。
+ 與左移輸出 <<。