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]
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?
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];}
You should return by reference. With your current version you are taking a copy and editing this copy which will not affect the original array. You have to change your operator overloading to this:
int& operator [] (int i){return H[i];}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.