c++ - 指向独立函数和 friend 函数的指针之间的区别

标签 c++ function-pointers friend-function

我不明白为什么以下内容无法编译(例如在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/

相关文章:

c++ - 如何通过指针输入整数数组并打印出数组和数组的大小(C++)

c++ - Boost::Variant and function_types in it: How to put functions into Boost::variant?

c++ - 友元函数访问静态库中定义的类的私有(private)成员

c++ - 定义 operator<< 内部类

c++ - 在 C++ 中返回位集 vector

c++ - 构造函数符号过多

c++ - 使用 C++/CLI 打开和读取 Excel 文件

c - 为什么结构体中的函数可以在 C 语言中使用

指向未确定类的成员函数的指针的 C++ 模板,具有不同的参数,称为参数

c++ - 为什么不能使用显式模板参数调用模板 friend 功能?