开发者

overloading -> operator in c++

I saw this code but I couldn't understand what it does:

inline S* O::operator->() const
{
    ret开发者_如何学编程urn ses; //ses is a private member of Type S*
}

so what happens now if I used ->?


Now if you have

O object;
object->whatever()

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

So

object->whatever();

is equivalent to pseudocode:

object.ses->whatever();

the latter would be of course impossible since O::ses is private - that's why I call it pseudocode.

With such overload you can create a wrapper around a pointer - such wrapper is typically called smart pointer.


Is you have an instance of class O and you do

obj->func()

then the operator-> returns ses and then it 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;
}


It's an overloaded operator that would return a pointer to some member of type S.

Like, if you write

O object;
(object->)...

the part (object->) would become your pointer.


Anytime an object of type O uses the -> operator a pointer to ses will be returned.


It overloads the operator -> of the class O, that returns now an S* instead of an O*

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜