小编use*_*855的帖子

重载运算符 - >

这是我的代码示例:

class X
{
public:
        void f() {}
};

class Y : public X
{
public:
        X& operator->() { return *this; }
        void f() {}
};

int main()
{
        Y t;
        t.operator->().f(); // OK
        t->f(); // error C2819: type 'X' does not have an overloaded member 'operator ->'
                // error C2232: '->Y::f' : left operand has 'class' type, use '.'
}
Run Code Online (Sandbox Code Playgroud)

为什么编译器试图将operator->的责任从Y移到X?当我实现X :: op->然后我不能返回X那里 - 编译错误说"无限递归",而从X :: op->返回一些Z再次说Z没有operator->,因此更高和等级越高.

谁能解释这个有趣的行为?:)

c++ overloading operator-keyword

18
推荐指数
2
解决办法
3638
查看次数

标签 统计

c++ ×1

operator-keyword ×1

overloading ×1