subscript operator on pointers

后端 未结 4 2317
醉梦人生
醉梦人生 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条回答
  •  萌比男神i
    2021-02-19 09:55

    It's because you can't overload operators for a pointer type; you can only overload an operator where at least one of the parameters (operands) is of class type or enumeration type.

    Thus, if you have a pointer to an object of some class type that overloads the subscript operator, you have to dereference that pointer in order to call its overloaded subscript operator.

    In your example, a has type MyClass*; this is a pointer type, so the built-in operator[] for pointers is used. When you dereference the pointer and obtain a MyClass, you have a class-type object, so the overloaded operator[] is used.

提交回复
热议问题