Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ overloading array operator

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!

like image 844
Daniel Avatar asked May 05 '16 05:05

Daniel


People also ask

Can [] operator be overloaded?

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: .

Can [] be overloaded in C++?

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.

How do you overload an operator?

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.

Which can overload a subscript operator?

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.


2 Answers

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];
like image 88
R Sahu Avatar answered Sep 19 '22 19:09

R Sahu


You can return references to what should be set. Add & to the return type.

int& operator [] (int i){return H[i];}
like image 38
MikeCAT Avatar answered Sep 21 '22 19:09

MikeCAT