c++ - 如何获取指向成员函数的指针?

标签 c++ pointer-to-member

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

void AsyncClass::method1()
{
    cout << "method is called" << endl;
}

void AsyncClass::method2()
{
    auto t = new std::thread(this->method1);
}

这两个方法都是公共(public)的且非静态的。这不会编译说

non-standard syntax; use '&' to create a pointer to member

同时考虑我尝试过的答案

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);

关于c++ - 如何获取指向成员函数的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33763011/

相关文章:

c++ - 如何定义和使用指向 "array"成员的指针?

c++ - 如何在类中传递函数作为参数?

c++ - 是否可以创建 3d 数组的指针数组?

c++ - 避免 gperf 输出文件中的 'warning: declaration UserSuppliedStruct does not declare anything'

c++ - 是否可以将一个 istream 扇出给多个读者?

c++ - constexpr和const之间的区别

c++ - 从模板创建通用打印函数以打印原始数据类型变量的值

c++ - 获取 const 方法的地址

c++ - 如何定义和设置指向模板类方法的函数指针

c++ - 具有成员函数指针的模板的默认值