You may miss a point on Meyers advice. The significant difference lies in the const modifier for the method.
This method is non-constant (note the const at the end), which means that it is allowed to change the state of the class.
int& operator[](const int index)
This method is constant ( const notice at the end)
const int operator[](const int index) const
As for the types of the parameter and the return value, there is a slight difference between int and const int , but this does not apply to the point of recommendation. What you should pay attention to is that non-constant overload returns int& , which means that you can assign it to it, for example. num[i]=0 , and const overload returns a non-modifiable value (regardless of the return type int or const int ).
In my personal opinion, if an object is passed by value , the const modifier is superfluous. This syntax is shorter and achieves the same
int& operator[](int index); int operator[](int index) const;
Andrey Aug 21 '12 at 8:40 2012-08-21 08:40
source share