首页 > 解决方案 > operator-> 有什么特别之处,它是如何工作的?

问题描述

#include <iostream>

class A
{
public:

    int a;
    int b;
    int c;
    int d;
};

class B
{
    A a;

public:

    B(int a, int b, int c, int d) : a{ a, b, c, d } {}

    A* operator->()
    {
        return &a;
    }

    A* operator++(int)
    {
        return &a;
    }

    A* pointer()
    {
        return &a;
    }
};

int main()
{
    B b(1, 2, 3, 4);

    //std::cout << b->->a << ' ' << b->->b << ' ' << b->->c << ' ' << b->->d << std::endl;

    std::cout << b->a << ' ' << b->b << ' ' << b->c << ' ' << b->d << std::endl;

//  std::cout << b.pointer()a << ' ' << b.pointer()b << ' ' 
//              << b.pointer()c << ' ' << b.pointer()d << std::endl; 

    std::cout << b.pointer()->a << ' ' << b.pointer()->b << ' ' 
                << b.pointer()->c << ' ' << b.pointer()->d << std::endl; 

    //std::cout << b++a << ' ' << b++b << ' ' << b++c << ' ' << b++d << std::endl;

    std::cout << b++->a << ' ' << b++->b << ' ' << b++->c << ' ' << b++->d << std::endl;
}

在这段代码中operator->,函数pointer返回完全相同的东西。但是,当我调用时,operator->我可以将b其视为实际指针。而如果我调用该函数pointer,我必须使用箭头运算符来访问a. 这也适用于operator++。这是一种独特的行为operator->吗?如何operator->工作?

标签: c++pointersoperator-overloadingoperators

解决方案


是的,这对于重载是特殊的operator->

(强调我的)

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

这意味着成员访问 like最后->a应用于返回的指针A*


推荐阅读