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

时间:2016-11-03 09:50:22

标签: 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&

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

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:1)

每当你的对象是非const时,非constness优先于constness。当左侧是非const时,将调用内部,当左侧是const时,将调用外部。

看看当内部被定义为:

时会发生什么

string operator+( const A& rhs ) const;