我不明白为什么以下内容无法编译(例如在gcc 9.10或MS VS C++ 2019中):
class X {
public:
friend bool operator==(int, X const &);
};
int main() {
2 == X(); // ok...
static_cast<bool (*)(int, X const &)>(&operator==); // Error: 'operator==' not defined
return 0;
}
但是下面的代码编译没有任何问题:class X {
public:
};
bool operator==(int, X const &);
int main() {
2 == X(); // ok...
static_cast<bool (*)(int, X const &)>(&operator==); // OK!
return 0;
}
我的期望是X的 friend 函数(operator ==)表现为独立函数(operator ==)。我缺少什么?谢谢
最佳答案
What I'm missing?
内联 friend 声明不会使该函数可用于普通名称查找。
请密切注意该错误。它并不表示函数的类型错误,它根本找不到名为
operator==
的东西。这是设计使然。内联 friend 定义只能由argument dependent lookup找到。普通查找(例如,命名函数以获取其地址)无法找到它。如果希望该功能可用于该目的,则必须提供一个命名空间范围的声明。
class X {
public:
friend bool operator==(int, X const &) { /* ... */ }
};
bool operator==(int, X const &);
关于c++ - 指向独立函数和 friend 函数的指针之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63226323/