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&
なぜ、クラス内の演算子が外部のものではなく呼び出されるようになっているのが好奇妙です。事業者間に何らかの優先順位がありますか?クラス内の演算子はどのように機能しますか?
同じ名前のいくつかの関数の中から選択するプロセスは、* overload resolution *と呼ばれます。このコードでは、非メンバは修飾変換( 'lhs'に' const 'を追加する)を必要とするがメンバは修飾しないため、メンバが優先されます。メンバ関数 'const'を作成した場合(これは' * this'を変更しないので)、曖昧になります –