subscript operator on pointers

后端 未结 4 2311
醉梦人生
醉梦人生 2021-02-19 09:31

If I have a pointer to an object that has an overloaded subscript operator ([]) why can\'t I do this:

 MyClass *a = new MyClass();
 a[1];

4条回答
  •  渐次进展
    2021-02-19 09:34

    Simply put, with a[1] the a pointer is treated as memory containing array, and you're trying to access the 2nd element in the array (which doesn't exist).

    The (*a)[1] forces to first get the actual object at the pointer location, (*a), and then call the [] operator on it.

提交回复
热议问题