一道关于重载operator->的编程问题

189 阅读1分钟
struct AAA {
    int arr[5];
    string name;
};

template<typename T>
struct BBB {
    T* a;
    T* operator->() {
        return a;
    }
};

int main()
{
    // b->name 被解释为 (b.operator->())->name  ???
    struct BBB<AAA> b;
    b->name = "hello";
    cout << sizeof(b->arr) << endl;
    cout << b->name << endl;
    return 0;
}

输出:
20
hello

========================================================
说明:
类成员访问运算符( -> )可以被重载,但它较为麻烦。它被定义用于为一个类赋予"指针"行为。运算符 -> 必须是一个成员函数。如果使用了 -> 运算符,返回类型必须是指针或者是类的对象。
参考链接:learn.jser.com/cplusplus/c…
【详解】blog.csdn.net/custa/artic…