班级内的操作员如何工作?

hjj*_*200 9 c++ operator-overloading operators

class A {
public:
    string operator+( const A& rhs ) {
        return "this and A&";
    }
};

string operator+( const A& lhs, const A& rhs ) {
    return "A& and A&";
}

string operator-( const A& lhs, const A& rhs ) {
    return "A& and A&";
}

int main() {
    A a;
    cout << "a+a = " << a + a << endl;
    cout << "a-a = " << a - a << endl;
    return 0;
}

//output
a+a = this and A&
a-a = A& and A&
Run Code Online (Sandbox Code Playgroud)

我很好奇为什么要调用类中的运算符而不是外部运算符.运营商之间是否有某种优先权?

Bat*_*eba 4

在多个同名函数中进行选择的过程称为重载决策。在此代码中,成员是首选,因为非成员需要资格转换(添加constlhs),但成员不需要。如果您创建了成员函数const(您应该这样做,因为它不会修改*this),那么它将是不明确的。