Overload & # 8594; operator in c ++

I saw this code, but I could not understand what it was doing:

inline S* O::operator->() const
{
    return ses; //ses is a private member of Type S*
}

so now if i used ->?

+5
source share
5 answers

You have an instance of class O and you do

obj->func()

then the-> operator returns ses, and then uses the returned pointer to call func ().

Full example:

struct S
{
    void func() {}
};

class O
{
public:
    inline S* operator->() const;
private:
    S* ses;
};

inline S* O::operator->() const
{
    return ses;
}

int main()
{
    O object;
    object->func();
    return 0;
}
+2
source

Now if you have

O object;
object->whatever()

first, the overloaded one will be called operator->, which will return what sesis stored inside the object, and then operator->(built-in in the case S*) will be called again for the returned pointer.

So,

object->whatever();

equivalent to pseudo code:

object.ses->whatever();

, O::ses - private - .

- ​​ .

+11

, S.

,

O object;
(object->)...

(object->) .

0

, O → , ses.

0

→ O, S * O *

-1

All Articles