C++ - overloading [] operator

后端 未结 2 685
渐次进展
渐次进展 2021-02-04 04:07

I have a template class Array:

template 
class Array {
    T TheArray[SIZE];
public:
    void Initialize() {
        for (int idx         


        
相关标签:
2条回答
  • 2021-02-04 04:09

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

    The const version will be called if this is a const pointer, else the non-const version will be called.

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

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

    0 讨论(0)
  • 2021-02-04 04:28

    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[]
    

    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.

    0 讨论(0)
提交回复
热议问题