C++ は常に、修飾子、private、scope、namespace などのアクセス指定子で最も近い「最適な一致」を使用します。
したがって、グローバル名前空間 operator!= とクラス 1 (メソッドが const の場合、class& または const class& であると想定される左側の引数が欠けている場合) は、内部にあります。クラス(名前空間)は、クラス内のものを取得します。
グローバル名前空間とクラスの間に 1 つしかない場合は、明らかにそれを取得します。
次のコードは、グローバル スコープとクラス スコープの間を示しています。const 修飾子などを追加することで、これを拡張できます。
#include <iostream>
using namespace std;
// Forward declaration to use without the class definition
class X;
bool operator!=( int lhs, const X& rhs) {
cout << "bool operator!=( int lhs, const X& rhs)" << endl;
return false;
}
bool operator!=(const X& lhs, const X& rhs) {
cout << "bool operator!=(const X& lhs, const X& rhs)" << endl;
return false;
}
bool operator!=(const X& lhs, int rhs) {
cout << "bool operator!=(const X& lhs, int rhs)" << endl;
return false;
}
// Note: Can't do: bool operator!=(int lhs, int rhs) -- already defined
class X {
private:
int x;
public:
X(int value) : x(value) { }
bool operator !=(const X& rhs) {
cout << "bool X::operator !=(const X& rhs)" << endl;
return true;
}
bool operator !=(int rhs) {
cout << "bool X::operator !=(int rhs)" << endl;
return true;
}
void f() {
X compare(1);
cout << "X::f()" << endl;
cout << (5 != 3) << endl; // Uses built-in
cout << (*this != 3) << endl; // Uses member function
cout << (*this != 1) << endl; // Uses member function
cout << (1 != *this) << endl; // There can be no member function, uses global namespace
cout << (*this != compare) << endl;
}
};
void f(const X& arg) {
cout << "f()" << endl;
X compare(1);
cout << (5 != 3) << endl; // Uses built in
cout << (arg != 3) << endl; // Uses global namespace
cout << (arg != 1) << endl; // Uses global namespace
cout << (1 != arg) << endl; // Uses global namespace
cout << (arg != compare) << endl; // Uses global namespace
}
int main(int argc, char **argv) {
X x(1);
x.f();
f(x);
return 0;
}