声明 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); }; /********** Begin / / End **********/ ostream& operator << (ostream& o, const Point& p) { o << '(' << p._x << ", " << p._y << ')'; return o; } int main() { int x,y; cin>>x>>y; Point p(x, y); cout << p << endl; cout << p++ << endl; cout << ++p << endl; cout << p-- << endl; cout << --p << endl; return 0; }
时间: 2023-08-15 09:07:12 浏览: 130
以下是对 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() {
int x, y;
cin >> x >> y;
Point p(x, y);
cout << p << endl;
cout << p++ << endl;
cout << ++p << endl;
cout << p-- << endl;
cout << --p << endl;
return 0;
}
```
以上代码演示了对 Point 类进行自增自减操作,并输出结果。
阅读全文