<分区>
考虑:
struct Y {
Y(float f) : f(f) {}
float f;
};
struct X {
X(Y y) : i(y.f) {}
int i;
friend bool operator==(X x1, X x2) {
return x1.i == x2.i;
}
};
int main()
{
return Y(1) == Y(2); // ERROR
}
这会导致 MSVC 上出现以下错误,Clang 上也会出现类似错误:
'==': candidate function(s) not accessible
could be the friend function at '..\main.cpp(11)' : '==' [may be found via argument-dependent lookup]
如果我将友元函数的定义移出类:
struct X {
X(Y y) : i(y.f) {}
int i;
friend bool operator==(X x1, X x2);
};
inline bool operator==(X x1, X x2)
{
return x1.i == x2.i;
}
上面 main()
中的表达式可以正常编译。
这是标准规定的还是错误?如果强制执行:为什么?