c++ two versions of overloading subscript operator

前端 未结 4 840
醉酒成梦
醉酒成梦 2021-01-04 14:32

My question is about the difference between:

const T& operator[](const int nIndex) const;

and:

T& operator[](const          


        
4条回答
  •  醉酒成梦
    2021-01-04 15:08

    The first one

    const T& operator[](const int nIndex) const;

    is a constant method(function) ie it guarantees that it would not change any of the class member variable(unless its mutable).

    It also returns a constant object which means you can call only constant function i.e you can call only functions that have const at the end similar to the one above.

    T& operator[](const int nIndex);

    This method may change the member variables and returns an object that can call any class methods.

    We need them both because the constant object would be using the constant method and non constant would be using the other one.

提交回复
热议问题