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

标签 c++ multithreading

在下面的代码中,在 线程 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/

相关文章:

c++ - "error: invalid function declaration"是什么意思?

c++ - 编译器是否优化了 `while(true)` 循环的条件检查? (C++)

c++ - 我可以方便地将 QVariant 转换回 QList<MyType> 吗?

c - 通知多个线程同时开始工作

java - 如果进程在外部被杀死则处理

c++ - fork进程之间的随机数是相同的

c++ - 移位运算符如何影响无符号数

python - 在 WSGI 环境中启动一个单独的线程

c - APUE 对 linux 线程的描述有误吗?

c - Eclipse:无法识别的选项 '-pthread'