Example 1: Overloading the []
operator for custom class objects to provide array-like behavior:
#include <iostream>
class MyArray {
public:
int data[5];
int& operator[](int index) {
if (index >= 0 && index < 5) {
return data[index];
} else {
throw std::out_of_range(“Index out of range”);
}
}
};
int main() {
MyArray arr;
for (int i = 0; i < 5; i++) {
arr[i] = i * 2;
}
std::cout << “Element at index 3: ” << arr[3] << std::endl;
// Uncommenting the line below will throw an exception:
// std::cout << “Element at index 10: ” << arr[10] << std::endl;
return 0;
}
Note: In this example, the []
operator is overloaded to provide array-like access to elements in a custom MyArray
class.
Example 2: Overloading the ==
operator for custom class objects to compare their equality:
#include <iostream>
class Point {
public:
int x;
int y;
Point(int xCoord, int yCoord) : x(xCoord), y(yCoord) {}
bool operator==(const Point& other) const {
return (x == other.x && y == other.y);
}
};
int main() {
Point p1(1, 2);
Point p2(1, 2);
Point p3(3, 4);
if (p1 == p2) {
std::cout << “p1 and p2 are equal.” << std::endl;
} else {
std::cout << “p1 and p2 are not equal.” << std::endl;
}
if (p1 == p3) {
std::cout << “p1 and p3 are equal.” << std::endl;
} else {
std::cout << “p1 and p3 are not equal.” << std::endl;
}
return 0;
}
Note: This example overloads the ==
operator to compare the equality of Point
objects based on their coordinates.