有没有办法在类指针类型的指针中调用类操作符而不使用*?

LxL*_*LxL 4 c++ operator-overloading

当我有一个指向类的指针时,是否可以在不使用*的情况下调用operator []?

   class MyClass
    {
    public:
        void operator[](int n)
        {
            cout<<"In []";
        }
    };
    int main()
    {
        MyClass *a=new MyClass;
        (*a)[2];//work
        a[2];//It just do some pointer arithmetic ...too bad :((
    }
Run Code Online (Sandbox Code Playgroud)

das*_*ght 6

是的,您应该能够使用->运算符,如下所示:

a->operator[] (2);
Run Code Online (Sandbox Code Playgroud)

在ideone上演示.

如果你只需要消除星号,这应该可以解决问题.如果您的目标是提高可读性,那么这没有多大帮助 - 您需要避开指针,或者使用常规成员函数:

class MyClass
{
public:
    void operator[](int n)
    {
        cout<<"In []";
    }
    // Add a regular function for use with pointers
    // that forwards the call to the operator[]
    void at(int n) { (*this)[n]; }
};
Run Code Online (Sandbox Code Playgroud)

现在你可以写了 a->at(2);

(演示中的演示).