I'm creating a Heap, like this:
struct Heap{
int H[100];
int operator [] (int i){return H[i];}
//...
};
When I try to print elements from it I do like this:
Heap h;
//add some elements...
printf("%d\n", h[3]); //instead of h.H[3]
My question is, if instead of accessing I want to set them, like this:
for(int i = 0; i < 10; i++) h[i] = i;
How can I do? I can't just do this way i did...
Thanks!
In the following example, a class called complx is defined to model complex numbers, and the + (plus) operator is redefined in this class to add two complex numbers. where () is the function call operator and [] is the subscript operator. You cannot overload the following operators: .
Subscripting [] Operator Overloading in C++ The subscript operator [] is normally used to access array elements. This operator can be overloaded to enhance the existing functionality of C++ arrays.
Operator Overloading in Binary Operators Here, + is a binary operator that works on the operands num and 9 . When we overload the binary operator for user-defined types by using the code: obj3 = obj1 + obj2; The operator function is called using the obj1 object and obj2 is passed as an argument to the function.
The subscript operator is most frequently overloaded when a class has an array as one of its data members. For example, the C++ string class has an array of char as one of its data members.
It is idiomatic to provide couple of overloads of the operator[]
function - one for const
objects and one for non-const
objects. The return type of the const
member function can be a const&
or just a value depending on the object being returned while the return type of the non-const
member function is usually a reference.
struct Heap{
int H[100];
int operator [] (int i) const {return H[i];}
int& operator [] (int i) {return H[i];}
};
This allows you to modify a non-const
object using the array operator.
Heap h1;
h1[0] = 10;
while still allowing you to access const
objects.
Heap const h2 = h1;
int val = h2[0];
You can return references to what should be set. Add &
to the return type.
int& operator [] (int i){return H[i];}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With