对指针的下标运算符 [英] subscript operator on pointers

查看:128
本文介绍了对指针的下标运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个指向一个具有重载下标运算符的对象( [] ),为什么我不能这样做:

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];

但是必须这样做:

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


推荐答案

这是因为您不能为指针重载运算符类型;你只能重载一个运算符,其中至少有一个参数(操作数)是类类型或枚举类型。

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.

在你的例子中, a 有类型 MyClass * ;这是一个指针类型,因此使用指针的内置 operator [] 。当您取消引用指针并获取 MyClass 时,您有一个类类型的对象,因此重载的 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.

这篇关于对指针的下标运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆