C++ 将始终使用在限定符、访问说明符(如私有、范围、命名空间等)中最接近的“最佳匹配”。
因此,如果有一个全局命名空间运算符!= 和一个类(缺少左侧参数,如果方法是 const,则假定为 class& 或 const class& - 它应该是),然后在里面类(命名空间),您将在类中获得一个。
如果全局命名空间和类之间只有一个,你显然会得到那个。
以下代码演示了全局和类范围之间的关系。您可以通过添加 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;
}