Point类运算符重载 声明Point类,有坐标x,y,为整型的私有数据成员。 声明成员函数: Point& operator++(); Point& operator+(Point); Point(int x = 0,int y =0); 声明友元函数: friend Point operator--(Point&,int); friend Point operator-(Point,Point); friend ostream& operator<<(ostream &,Point p); 注意:若一个函数返回的是对象引用,则不返回auto型对象,需要静态存储的对象, 如static类型的对象 主函数中定义Point类的三个对象:p1、p2、p,p1、p2的初始值由键盘输入,p使用默认值。依次实现运算:p=++p1; p=p2--; p=p1+p2; p=p1-p2;后将结果输出。注意结果输出要求使用类似于“cout<<p1;”的形式。
时间: 2023-12-02 14:05:44 浏览: 103
以下是Point类的实现代码:
```cpp
#include<iostream>
using namespace std;
class Point {
private:
int x, y;
public:
Point(int x = 0, int y = 0) {
this->x = x;
this->y = y;
}
Point& operator++() { // ++p
++x;
++y;
return *this;
}
Point& operator+(Point p) { // p1 + p2
static Point result;
result.x = x + p.x;
result.y = y + p.y;
return result;
}
friend Point operator--(Point& p, int) { // p--
Point temp(p);
--p.x;
--p.y;
return temp;
}
friend Point operator-(Point p1, Point p2) { // p1 - p2
static Point result;
result.x = p1.x - p2.x;
result.y = p1.y - p2.y;
return result;
}
friend ostream& operator<<(ostream& os, Point p) { // cout << p
os << "(" << p.x << "," << p.y << ")";
return os;
}
};
int main() {
int x1, y1, x2, y2;
cin >> x1 >> y1 >> x2 >> y2;
Point p1(x1, y1), p2(x2, y2), p;
p = ++p1;
cout << p << endl;
p = p2--;
cout << p << endl;
p = p1 + p2;
cout << p << endl;
p = p1 - p2;
cout << p << endl;
cout << p1 << endl;
cout << p2 << endl;
return 0;
}
```
示例输入:
```
1 2 3 4
```
示例输出:
```
(2,3)
(3,4)
(6,8)
(-2,-4)
(2,3)
(2,3)
```
阅读全文