c++ two versions of overloading subscript operator

前端 未结 4 816
醉酒成梦
醉酒成梦 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:01

    Those are member functions of a class, and the version will be chosen based on whether that class in used as a const context.

    This version will be called when [] is used on a object in a const context. It preserves the const-ness of the returned element.

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

    This version will be called when [] is used on a non-const object. It specifies that when your object isn't const, you'll get an element that you can modify, allowing code like myObject[0] = 10;

    T& operator[](const int nIndex);
    

提交回复
热议问题