声明 Point 类,有坐标 _ x,_ y 两个成员变量;对Point 类重载“++”(自增)、“--”(自减)运算符,实现对坐标值的改变include <iostream> using namespace std; class Point { int _x, _y; public: Point(int x=0, int y=0) : _x(x), _y(y) {} Point& operator++(); Point operator++(int); Point& operator--(); Point operator--(int); friend ostream& operator << (ostream& o, const Point& p); };
时间: 2023-08-21 11:21:15 浏览: 277
这段代码已经声明了 Point 类,你可以在其它地方使用该类来创建 Point 对象,并进行自增自减操作。以下是完整的代码实现:
```c++
#include <iostream>
using namespace std;
class Point {
int _x, _y;
public:
Point(int x=0, int y=0) : _x(x), _y(y) {}
Point& operator++();
Point operator++(int);
Point& operator--();
Point operator--(int);
friend ostream& operator << (ostream& o, const Point& p);
};
Point& Point::operator++() {
++_x;
++_y;
return *this;
}
Point Point::operator++(int) {
Point temp(*this);
++(*this);
return temp;
}
Point& Point::operator--() {
--_x;
--_y;
return *this;
}
Point Point::operator--(int) {
Point temp(*this);
--(*this);
return temp;
}
ostream& operator << (ostream& o, const Point& p) {
o << "(" << p._x << ", " << p._y << ")";
return o;
}
int main() {
Point p1(1, 1);
cout << "p1: " << p1 << endl;
++p1;
cout << "p1 after prefix ++: " << p1 << endl;
p1++;
cout << "p1 after postfix ++: " << p1 << endl;
--p1;
cout << "p1 after prefix --: " << p1 << endl;
p1--;
cout << "p1 after postfix --: " << p1 << endl;
return 0;
}
```
以上代码演示了对 Point 类进行自增自减操作,并输出结果。
阅读全文
相关推荐

















