重载运算符 ->

Mis*_*tyD 5 c++ pointers operator-overloading

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

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
}
Run Code Online (Sandbox Code Playgroud)

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

std::cout << a->->p; //The first arrow returns the pointer 
                     //the second arrow dereferences it
Run Code Online (Sandbox Code Playgroud)

但在这里,单个箭头似乎不仅返回指针,而且还取消引用它。这是 C++ 中的特殊情况吗?

son*_*yao 5

是的,这是设计使然,operator->将在返回值上递归调用;那么我们就可以像原始指针一样使用这样的类(所谓的智能指针)。

operator->如果提供了用户定义的,operator->则将在其返回的值上再次递归调用,直到operator->到达返回普通指针的 an。之后,内置语义将应用于该指针。