C ++-重载[]运算符 [英] C++ - overloading [] operator
问题描述
我有一个模板类Array:
I have a template class Array:
template <class T=int, int SIZE=10>
class Array {
T TheArray[SIZE];
public:
void Initialize() {
for (int idx=0; idx < SIZE; idx++) {
TheArray[idx] = T();
}
}
T& operator [](int idx) {
return TheArray[idx];
}
T operator [](int idx) const {
return TheArray[idx];
}
}
我对运算符 []
重载有一些疑问(我在网上找到了这个示例).
I have some questions on operator []
overloading (I found this example on net).
我了解 T&运算符[](int idx)
返回对索引为 idx
的数组值的引用,而 T运算符[](int idx)const
返回其值.但是,我不确定在哪种情况下使用 []
运算符会返回引用或值.
I understand that T& operator [](int idx)
returns a reference to an array value with index idx
and that T operator [](int idx) const
returns its value.
However, I am not sure in which case a reference or a value will be returned by using the []
operator.
此外,如果我更改 T运算符[](int idx)const
-> T运算符[](int idx)
,编译器会抱怨.这是为什么?我能理解编译器会抱怨,因为只有返回类型不同,但是为什么在添加 const
时它不会抱怨呢?这仅意味着没有任何类的内部构造被修改,对吧?
Also, if I change T operator [](int idx) const
-> T operator [](int idx)
, the compiler complains. Why is that?
I can understand that the compiler complains because only the return type is different, but why doesn't it complain when const
is added? This only means that none of the class internals are modified, right?
我试图调试这个小的主要实现:
I tried to debug this small main implementation:
int main() {
int val;
Array<> intArray;
intArray.Initialize();
val = intArray[1];
printf("%d", intArray[1]);
intArray[1] = 5;
}
并且每次 T&运算符[](int idx)
被调用.为什么?
And each time T& operator [](int idx)
is called. Why?
谢谢.
推荐答案
operator []
重载将基于调用对象的 const
限定条件进行选择
The operator[]
overload will be selected based on the const
-qualification of the object you call it on.
Array<> intArray;
intArray[1]; //calls T& operator[]
const Array<> constArray;
constArray[1]; //calls T operator[]
如果从 T运算符[]
中删除 const
,则会出现错误,因为成员函数不能具有相同的 const
限定和参数,因为将无法在它们之间进行选择.
If you remove the const
from T operator[]
, you get an error because the member functions cannot have the same const
-qualification and parameters as there would be no way to select between them.
这篇关于C ++-重载[]运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!