overload array operator cpp
The array operator in C++ can be overloaded to provide custom behavior when accessing elements of an object as if it were an array. Here is an example of how to overload the array operator in C++:
#include <iostream>
class MyClass {
private:
int data[5];
public:
int& operator[](int index) {
return data[index];
}
};
int main() {
MyClass obj;
// Assign values to the array elements
for (int i = 0; i < 5; i++) {
obj[i] = i + 1;
}
// Access and print the array elements
for (int i = 0; i < 5; i++) {
std::cout << obj[i] << " ";
}
return 0;
}
Explanation of each step:
We include the
<iostream>
library to use the standard input/output stream objects such asstd::cout
.We define a class called
MyClass
which will have an array of integers calleddata
as its private member.We define the array operator
[]
as a member function of theMyClass
class. It takes an integer index as a parameter and returns a reference to an integer. By returning a reference, we can both read and modify the array elements through the overloaded operator.Inside the
operator[]
function, we simply return the value at the specified index of thedata
array.In the
main()
function, we create an object of theMyClass
class calledobj
.We use a
for
loop to assign values to the elements of theobj
array using the overloaded array operator. The loop runs from0
to4
, and we assign the values1
to5
to the corresponding array elements.Another
for
loop is used to access and print the elements of theobj
array using the overloaded array operator. The loop also runs from0
to4
, and we print each element followed by a space.Finally, we return
0
to indicate successful execution of the program.
This is a basic example of overloading the array operator in C++. You can customize the behavior of the operator based on your specific requirements.