9

据说箭头运算符是递归应用的。但是当我尝试执行以下代码时,它会在应该打印 4 时打印乱码。

class dummy
{
public:
    int *p;

    int operator->()
    {
        return 4;
    }
};

class screen 
{
public:
    dummy *p;

    screen(dummy *pp): p(pp){}
    dummy* operator->()
    {
        return p;
    }
};

int main()
{
    dummy *d = new dummy;
    screen s(d);
    cout<<s->p;
    delete d;
}
4

3 回答 3

14
于 2012-05-05T09:56:30.983 回答
2

C++ Primer (5th edition) formulates it as follows on page 570:

The arrow operator never loses its fundamental meaning of member access. When we overload arrow, we change the object from which arrow fetches the specified member. We cannot change the fact that arrow fetches a member.

于 2015-07-24T10:50:46.300 回答
1

The deal is once screen::operator->() returns a pointer (dummy*) the recursion stops because built-in (default) -> in used on that pointer. If you want recursion you should return dummy or dummy& from screen::operator->()

于 2012-05-05T09:57:40.383 回答