C++ - 重载[]运算符

Moj*_*o28 14 c++ overloading operator-overloading operator-keyword

我有一个模板类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];
    }
}
Run Code Online (Sandbox Code Playgroud)

我有一些关于运算符[]重载的问题(我在网上找到了这个例子).

我理解T& operator [](int idx)返回引用带索引的数组值idxT operator [](int idx) const返回其值.但是,我不确定在哪种情况下使用[]运算符将返回引用或值.

另外,如果我改变T operator [](int idx) const- > T operator [](int idx),编译器会抱怨.这是为什么?我可以理解编译器抱怨因为只有返回类型不同,但是为什么它在const添加时不会抱怨?这只意味着修改了类的内部,对吧?

我试图调试这个小的主要实现:

int main() {
    int val;
    Array<> intArray;

    intArray.Initialize();
    val = intArray[1];
    printf("%d", intArray[1]);
    intArray[1] = 5;
}
Run Code Online (Sandbox Code Playgroud)

每次都T& operator [](int idx)被召唤.为什么?

提前致谢.

Tar*_*ama 16

operator[]过载将根据选择const调用它的对象的企业资质.

Array<> intArray;
intArray[1]; //calls T& operator[]

const Array<> constArray;
constArray[1]; //calls T operator[]
Run Code Online (Sandbox Code Playgroud)

如果删除constfrom T operator[],则会出现错误,因为成员函数不能具有相同的const-qualification和参数,因为无法在它们之间进行选择.


Bat*_*eba 12

首先,[]作为呼唤的语法糖this->operator[].

const如果thisconst指针则调用该版本,否则const将调用非版本.

继续,您应该使用const T& operator [](int idx) const {,即让const版本返回const引用.这将节省深度复制的开销.

最后,const函数的性质其签名的一部分.这允许您基于const-ness 重载.否则你不能拥有这两个版本operator[].