C++ - 重载 [] 运算符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34593263/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 14:24:17  来源:igfitidea点击:

C++ - overloading [] operator

c++operator-overloadingoverloadingoperator-keyword

提问by Mojo28

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).

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

I understand that T& operator [](int idx)returns a reference to an array value with index idxand that T operator [](int idx) constreturns its value. However, I am not sure in which case a reference or a value will be returned by using the []operator.

我知道T& operator [](int idx)返回对带有索引的数组值的引用idxT operator [](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 constis added? This only means that none of the class internals are modified, right?

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

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;
}

And each time T& operator [](int idx)is called. Why?

并且每次都T& operator [](int idx)被调用。为什么?

Thanks in advance.

提前致谢。

回答by TartanLlama

The operator[]overload will be selected based on the const-qualification of the object you call it on.

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

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

const Array<> constArray;
constArray[1]; //calls T operator[]

If you remove the constfrom 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.

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

回答by Bathsheba

First thing, regard []as syntactic sugar for calling this->operator[].

首先,将 .[]视为调用的语法糖this->operator[]

The constversion will be called if thisis a constpointer, else the non-constversion will be called.

const如果版本将被称为this是一个const指针,否则非const版本将被调用。

Moving on, you ought to use const T& operator [](int idx) const {, i.e. have the constversion return a constreference. That will save the overhead of taking a deep copy.

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

Finally, the const-ness of a function ispart of its signature. This allows you to overload based on const-ness. Otherwise you couldn't have the two versions of operator[].

最后,const函数的-ness其签名的一部分。这允许您基于const-ness进行重载。否则,您将无法拥有operator[].