指向成员函数语法的指针

Pointer to member function syntax

我正试图围绕指向成员函数的指针进行思考,并被这个例子所困:

#include <iostream>

class TestClass {
  public:
    void TestMethod(int, int) const;
};

void TestClass::TestMethod(int x, int y) const {
  std::cout << x << " + " << y << " = " << x + y << std::endl;
}

int main() {
  void (TestClass::*func)(int, int) const;
  func = TestClass::TestMethod;

  TestClass tc;
  tc.func(10, 20);

  return 0;
}

我认为代码应该做什么:

我遇到两个编译错误:

我做错了什么?

func = TestClass::TestMethod;应该是func = &TestClass::TestMethod;tc.func(10, 20)应该是(tc.*func)(10, 20)(后面注意有两个 更改:. 变为 .*,并且添加了括号;两者都是必需的)。

简单的语法细节。

func = &TestClass::TestMethod;
//     ^ Missing ampersand to form a pointer-to-member

TestClass tc;
(tc.*func)(10, 20);
// ^^ Using the dot-star operator to dereference the pointer-to-member,
// while minding its awkward precedence with respect to the call operator.

指向成员(函数或其他)的指针与常规指针有很大不同,尽管在语法上有一些相似之处。常规函数充当函数指针的方式,反之亦然,是从 C 继承的,但 C 不支持指向成员的指针,因此 C++ 中没有必要以这种方式工作。

要创建指向成员的指针,您必须显式使用 &,并且必须显式使用 .* 来间接指向它,如果您不这样做,这可能更符合您的期望不习惯函数在 C 中的工作方式:

func = &TestClass::TestMethod;
(tc.*func)(10, 20);