使用类函数创建线程时出错

error while creating a thread with a class function

本文关键字:出错 线程 创建 类函数      更新时间:2023-10-16

在下面的代码中,在thread t(&Fred::hello),我得到一个错误,该术语不评估为一个函数接受0个参数。问题是什么?

#include <iostream>
#include <thread>
using namespace std;
class Fred
{
public:
virtual void hello();
};
void Fred::hello()
{
cout << "hello" << endl;
}
int main()
{
thread t (&Fred::hello);
t.join();
return 0;
}

T的非静态成员函数需要在T的实例上调用,并且需要一个隐式的第一个形参类型为T*(或const,和/或volatile T*)。

Fred f;
f.hello()

等价于

Fred f;
Fred::hello(&f);

因此,当向线程构造函数传递非静态成员函数时,还必须传递隐含的第一个参数:

Fred f;
std::thread t(&Fred::hello, &f);