为什么成员函数指针需要 & 而不是普通函数指针?

Why is & needed for member function pointers, not for normal function pointers?

本文关键字:函数 指针 成员 为什么      更新时间:2023-10-16

我理解我的第二个陈述"why &一般的函数指针不需要",因为函数名本身就是函数的地址。

我不明白的是为什么成员函数指针严格需要'&' ?

例子:普通函数指针:

int add(int a, int b) {
  return (a + b);
}
int (*fp)(int, int);
fp = add;
(*fp)(2, 3) // This would give me addition of a and b, i.e. 5

成员函数指针

class ABC {
  public:
    int i;
    ABC() { i = 0; }
    int addOne(int j) {
      return j + 1;
    }
};
// Member function pointer
int (ABC::*mfp)(int); 
// This is what I am talking about. '&' in below line.
mfp = &ABC::addOne;
ABC abc;
std::cout << (abc.*mfp)(2) << std::endl;

在我看来,成员函数指针的寻址操作符是必要的,因为声明的右侧(rhs)是常量而不是变量。

我们不会说

 int (ABC::*mfp)(int); 
 mfp = ABC::addOne();

因为这将调用一个函数

而且,作用域解析符operator::在c++操作符优先级表

中具有最高的优先级。https://github.com/MicrosoftDocs/cpp-docs/blob/master/docs/cpp/cpp-built-in-operators-precedence-and-associativity.md

::操作符在rhs上的任何其他操作符之前求值。我猜编者会想:"嗯……那是什么?这应该是一个函数,但是…",然后看到地址操作符,并知道开发人员需要什么。