重载 operator+ 两次(内部和外部 class)

overloading operator+ twice (inside and outside class)

为什么允许我这样做,为什么没有歧义抱怨,为什么 class' 方法先于另一个选择?

class EX
{
public:
    //...

    void operator+(const EX& ref)
    {
        cout << "A";
    }
};

void operator+(const EX& ref1, const EX& ref2)
{
    cout << "B" << endl;
}

int main()
{
    EX obj1{20};
    EX obj2{30};


    cout << "obj1 + obj2 = " <<  obj1 + obj2 << endl;

    return 0;
}

我希望全局函数 operator+ 被称为 "B" 打印在屏幕上,而不是 "A" 被打印出来。

您的成员重载仅接受 EX 的非常量实例作为第一个操作数,而自由重载接受常量和非常量实例。根据重载决议规则,非常量胜出,因为它与传入的类型完全匹配。

如果使成员重载为 const,将出现歧义错误,表明 *this 是 const:

void operator+(const EX& ref) const
{
    cout << "A";
}