如何获取指向成员函数的指针

How to obtain a pointer to member function?

本文关键字:函数 指针 成员 何获 取指      更新时间:2023-10-16

我知道这个问题会被标记为重复,因为我也在SO上读过几个类似的问题。但不幸的是,没有一个答案对我有效。我尝试了所有的问题,这是我想问的最后一个选项。

void AsyncClass::method1()
{
    cout << "method is called" << endl;
}
void AsyncClass::method2()
{
    auto t = new std::thread(this->method1);
}

这两种方法都是公共的和非静态的。这不是编译说

非标准语法;使用"&"创建指向成员的指针

还考虑到SO上的答案,我尝试了

auto t = new std::thread(this->method1);
auto t = new std::thread(this->*method1);
auto t = new std::thread(&(this->method1));
auto t = new std::thread(&AsyncClass::method1);

他们都没有编译。正确的方法是什么?

您应该做:

auto t = new std::thread(&AsyncClass::method1, this);