fork download
  1. #include <iostream>
  2.  
  3. class Point {
  4. private:
  5. int x;
  6. int y;
  7. static int numPoints;
  8.  
  9. public:
  10. // Constructors
  11. Point() : x(0), y(0) {
  12. numPoints++;
  13. }
  14.  
  15. Point(int x, int y) : x(x), y(y) {
  16. numPoints++;
  17. }
  18.  
  19. // Copy constructor
  20. Point(const Point &other) : x(other.x), y(other.y) {
  21. numPoints++;
  22. }
  23.  
  24. // Destructor
  25. ~Point() {
  26. numPoints--;
  27. }
  28.  
  29. // Overloaded input stream operator
  30. friend std::istream& operator>>(std::istream &in, Point &point) {
  31. in >> point.x >> point.y;
  32. return in;
  33. }
  34.  
  35. // Overloaded output stream operator
  36. friend std::ostream& operator<<(std::ostream &out, const Point &point) {
  37. out << point.x << " " << point.y;
  38. return out;
  39. }
  40.  
  41. // Overloaded unary minus (-) operator
  42. Point operator-() const {
  43. return Point(-x, -y);
  44. }
  45.  
  46. // Overloaded binary plus (+) operator
  47. Point operator+(const Point &other) const {
  48. return Point(x + other.x, y + other.y);
  49. }
  50.  
  51. // Overloaded postfix increment (++) operator
  52. Point operator++(int) {
  53. Point temp(*this);
  54. x++;
  55. y++;
  56. return temp;
  57. }
  58.  
  59. // Overloaded equality (==) operator
  60. bool operator==(const Point &other) const {
  61. return (x == other.x) && (y == other.y);
  62. }
  63.  
  64. // Overloaded subscript operator for access to x and y
  65. int operator[](int index) const {
  66. return (index == 0) ? x : ((index == 1) ? y : 0);
  67. }
  68.  
  69. // Const member function to get the number of points
  70. static int getNumPoints() {
  71. return numPoints;
  72. }
  73. };
  74.  
  75. // Initialize static member numPoints
  76. int Point::numPoints = 0;
  77.  
  78. int main() {
  79. std::cout << std::endl;
  80.  
  81. Point p1;
  82. Point p2(3, 5);
  83.  
  84. std::cout << "Enter x and y values: ";
  85. std::cin >> p1;
  86. std::cout << p1 << " " << -p2 << std::endl;
  87. std::cout << (p1 + p2) << std::endl;
  88. std::cout << (p2++) << std::endl;
  89. std::cout << p2 << std::endl;
  90. std::cout << (p1 == p2) << std::endl;
  91. std::cout << p1[1] << " " << p1[0] << std::endl; // Corrected the order of indices
  92. std::cout << Point::getNumPoints() << std::endl;
  93.  
  94. std::cout << std::endl;
  95. return 0;
  96. }
  97.  
Success #stdin #stdout 0.01s 5304KB
stdin
20
30
stdout
Enter x and y values: 20 30 -3 -5
23 35
3 5
4 6
0
30 20
2