类中的操作符是如何工作的

How does an operator inside a class work?

本文关键字:工作 何工作 操作符      更新时间:2023-10-16
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&

我很好奇为什么调用类内部的操作符而不是外部的操作符。运营商之间是否存在某种优先权?

在多个同名函数中进行选择的过程称为重载解析。在这段代码中,成员是首选的,因为非成员需要资格转换(将const添加到lhs),而成员不需要。如果您将成员函数设置为const(您应该这样做,因为它不修改*this),那么它将是不明确的。

当你的对象是非const时,非const优先于const。当左侧为非const时调用内部函数,当左侧为const时调用外部函数。

看看当inner定义为:

时会发生什么

string operator+( const A& rhs ) const;