【发布时间】:2017-03-16 20:28:25
【问题描述】:
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),那么它会是模棱两可的
标签: c++ operator-overloading operators