坐标点Point的运算符重载.cpp 902 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #include <iostream>
  2. using namespace std;
  3. class Point {
  4. private:
  5. int _x, _y;
  6. public:
  7. Point(int x, int y) : _x(x), _y(y) {}
  8. //前置
  9. Point& operator++() {
  10. ++_x;
  11. ++_y;
  12. return *this;
  13. }
  14. //后置
  15. Point operator++(int) {
  16. Point temp = *this;
  17. _x++;
  18. _y++;
  19. return temp;
  20. }
  21. Point& operator--() {
  22. --_x;
  23. --_y;
  24. return *this;
  25. }
  26. Point operator--(int) {
  27. Point temp = *this;
  28. _x--;
  29. _y--;
  30. return temp;
  31. }
  32. friend ostream& operator<<(ostream& os, const Point& p) {
  33. os << "(" << p._x << ", " << p._y << ")";
  34. return os;
  35. }
  36. friend istream& operator>>(istream& is, Point& p) {
  37. is >>p._x >> p._y;
  38. return is;
  39. }
  40. };
  41. int main() {
  42. Point p(1,2);
  43. cin >> p;
  44. cout << p << endl;
  45. Point p1 = p++;
  46. cout << p1 << endl;
  47. Point p2 = ++p;
  48. cout << p2 << endl;
  49. Point p3 = p--;
  50. cout << p3 << endl;
  51. Point p4 = --p;
  52. cout << p4 << endl;
  53. return 0;
  54. }