重载运算符->

overloading the operator ->

我正在考虑重载 -> 运算符。我想到了以下简单示例:

struct foo
{
    int p = 12;
};

struct A
{    
    foo* f;
    A()
    {
        this->f = new foo();
    }
    foo* operator-> ()
    {
        return f;
    }
};

int main()
{
    A a;
    std::cout << a->p; //output 12
}

虽然这个例子有效,但我希望有人能告诉我为什么它有效。 我在想它应该像这样工作

std::cout << a->->p; //The first arrow returns the pointer 
                     //the second arrow dereferences it

但这里看起来像一个箭头,不仅 returns 指针而且还取消引用它。这是 C++ 中的特例吗?

是的,这是by-design,operator->会在return值上递归调用;那么我们可以像原始指针一样使用这样的class(so-called智能指针)。

If a user-defined operator-> is provided, the operator-> is called again on the value that it returns, recursively, until an operator-> is reached that returns a plain pointer. After that, built-in semantics are applied to that pointer.