简体   繁体   中英

Overloading operators * and ->

I tried to overload the dereference operators ( * ) and ( -> ) for a simple class.

class Base
{
private:
    int i;
    int j;

public:
    Base(int i): i(i), j(i), k(90) { }

    void print() 
    { 
        cout << i << j << endl; 
    }

    Base &operator*(void)
    {
        cout << "inside * operator" << endl;

        return *this;

    }

    Base *operator->(void)
    {
        cout << "inside -> operator" << endl;

        return this;
    }
};

int main()
{
    Base *b = new Base(100);

    int j = b->k;

    int l = (*b).k;

    cout << j << l<< endl;

    return 0;
}

Here the overloaded operator -> does not get called. But when I use int j = (*b)->k , then the overloaded operator -> gets called.

I did not understand this why it is so? and also i didn't able to call overloaded operator* at all. I understand that we overload such operators mainly for smart pointers but i didnt get the reason here. any help???

b is a pointer. The -> and * operators you are applying to b de-reference the pointer, not the thing it points to. Furthermore, the language does not allow you to overload those operators for pointer types.

The overloaded * and -> operators are only used if the left-hand side of the operator is an object of type Base , but in the example you have above, the left-hand side of the operator is a pointer of type Base* . To invoke operator* or operator -> , you'll need to use actual, concrete Base objects. For example:

Base b{100};
*b = ...
b->...

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM