数组运算符[]重载const和非const版本 [英] Array operator [] overloading const and non-const versions
问题描述
我得到了一个实现模板数组类的任务.要求之一是重载[]运算符.我制作了这两个const和非const版本,它们似乎运行良好.
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
和
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]
在非常量数组上吗?
推荐答案
总是在非const数组上调用非const函数,而在const数组上调用const函数.
The non-const function will always be called on a non-const array, and the const function on a const array.
当两个具有相同名称的方法时,编译器会根据参数的类型和隐式对象参数(arr)的类型来选择最适合的一个.
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).
前几天我刚刚回答了一个类似的问题,您可能会发现有帮助: https://stackoverflow.com/a/16922652/2387403
I just answered a similar question the other day, you may find it helpful: https://stackoverflow.com/a/16922652/2387403
这篇关于数组运算符[]重载const和非const版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!