C++ - overloading [] operator

后端 未结 2 684
渐次进展
渐次进展 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: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.

提交回复
热议问题