有没有什么办法调用类运算符out使用*,在类类型的指针? [英] Is there any way to call class operators with out using * , in a pointer to class type?

查看:107
本文介绍了有没有什么办法调用类运算符out使用*,在类类型的指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible to call operator[] with out using * when I have a pointer to the class ?

   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 :((
    }


推荐答案

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

Yes, you should be able to use the -> operator, like this:

a->operator[] (2);

在ideone上演示。

如果所有你需要的是消除星号,这应该做的窍门如果你的目标是一个更好的可读性,这不是很有帮助 - 你需要要么避免指针,要么使用正常的成员函数:

If all you need is eliminating the asterisk, this should do the trick. If you are aiming for a better readability, this isn't of much help - you need to either avoid the pointer, or to use a regular member function:

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

现在您可以在(2)写 a->;

Now you can write a->at(2);

在ideone上演示)。

这篇关于有没有什么办法调用类运算符out使用*,在类类型的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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