问题
I got an assignment to implement a template array class. One of the requirement is to overload the [] operator. I made this two const and non-const version which seems to be working fine.
const T& operator[](const unsigned int index)const
and
T& operator[](const unsigned int index)
My question is how will the compiler know which one to run when i will do something like:
int i=arr[1]
On a non-const array?
回答1:
The non-const function will always be called on a non-const array, and the const function on a const array.
When you have two methods with the same name, the compiler selects the best-fitting one based on the type of the arguments, and the type of the implicit object parameter (arr).
I just answered a similar question the other day, you may find it helpful: https://stackoverflow.com/a/16922652/2387403
回答2:
It all depends on your declaration of the object. If you have
const T arr[];
...
int i=arr[1];
Then the const version will be called, but if you have
T arr[];
...
int i=arr[1];
Then the non-const version will be called. So in the example you gave, since it was a non-const array, the non-const version will be called.
来源:https://stackoverflow.com/questions/16948567/array-operator-overloading-const-and-non-const-versions