It's possible to overload operator[] to take one argument, in the brackets. However how can I overload this operator to allow the user to type object[a] = b?
Asked
Active
Viewed 52 times
0
user3150201
- 1,751
- 5
- 23
- 27
-
Of course, you decide whatever is returned, and whatever is returned by the operator can be assigned to – Gunther Van Butsele Oct 11 '14 at 18:00
-
1Technically the way of speaking about it is that your operator needs to return an "[LValue](http://stackoverflow.com/questions/3601602/what-are-rvalues-lvalues-xvalues-glvalues-and-prvalues)"...which means it can appear on the left-hand side of an assignment. So basically return a non-const reference that can be a target of the kind of assignment you want to make, and is a meaningful place to be targeting said assignment. – HostileFork says dont trust SE Oct 11 '14 at 18:03
3 Answers
2
You return a reference to your item, something like:
A &operator[](int pos) { return list[pos]; }
So when you say object[a]=b; it's actually translated to:
A &tmp=object[a];
tmp=b;
Or in more clear terms:
A *tmp=object[a]; // more or less a pointer
*tmp=b; // you replace the value inside the pointer
Blindy
- 60,429
- 9
- 84
- 123
1
The general declaration of the operator (it shall be a class member function) is the following
ObjectElementType & operator []( size_t );
Vlad from Moscow
- 265,791
- 20
- 170
- 303
1
Subscript operators often comes in pair :-
T const& operator[] (size_t ) const;
T& operator[] (size_t ); // This enables object[a] = b on non-const object
P0W
- 44,365
- 8
- 69
- 114