Array operator [] overloading const and non-const versions

流过昼夜 提交于 2020-07-11 04:08:42

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!