坐标点Point的运算符重载.cpp 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #include <iostream>
  2. class Point {
  3. private:
  4. int _x;
  5. int _y;
  6. public:
  7. Point(int x, int y) : _x(x), _y(y) {}
  8. Point& operator++() {
  9. _x++;
  10. _y++;
  11. return *this;
  12. }
  13. Point operator++(int) {
  14. Point temp = *this;
  15. _x++;
  16. _y++;
  17. return temp;
  18. }
  19. Point& operator--() {
  20. _x--;
  21. _y--;
  22. return *this;
  23. }
  24. Point operator--(int) {
  25. Point temp = *this;
  26. _x--;
  27. _y--;
  28. return temp;
  29. }
  30. void display() {
  31. std::cout << "(" << _x << ", " << _y << ")";
  32. }
  33. };
  34. int main() {
  35. int x, y;
  36. std::cin >> x >> y;
  37. Point point(x, y);
  38. Point temp0 = point;
  39. temp0.display();
  40. std::cout << std::endl;
  41. // 后置和前置“++”运算
  42. Point temp1 = point++;
  43. temp1.display();
  44. std::cout << std::endl;
  45. ++point;
  46. point.display();
  47. std::cout << std::endl;
  48. // 后置和前置“--”运算
  49. Point temp2 = point--;
  50. temp2.display();
  51. std::cout << std::endl;
  52. --point;
  53. point.display();
  54. std::cout << std::endl;
  55. return 0;
  56. }