在下面的代码中,在 线程 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);
关于c++ - 使用类函数创建线程时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16485655/