Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to call class operators with out using * , in a pointer to class type?

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 :((
    }
like image 703
uchar Avatar asked Mar 20 '23 15:03

uchar


1 Answers

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

a->operator[] (2);

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

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

(Demo on ideone).

like image 91
Sergey Kalinichenko Avatar answered Apr 06 '23 20:04

Sergey Kalinichenko