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
),那么它将是模棱两可的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句