我尝试运行一个函数,它启动线程,但我收到错误:
error: invalid use of non-static member function ‘void Sniffer::f1(int)’
代码:
#include "library.hpp"
class Sniffer
{
void f1( int x );
void f2();
};
void Sniffer::f1( int x )
{
while (true)
{
sleep(x);
std::cout << 1 << std::endl;
}
}
void Sniffer::f2()
{
int y = 5;
std::thread t1( f1, y );
t1.join();
}
int main()
{
return 0;
}
任何其他方式,在不改变函数的情况下修复它,在静态函数上?
在 C++ 中,成员函数有一个隐式的第一个参数绑定到this
. 创建线程时,this
必须传递指针。您还必须使用类名限定成员函数。您的情况下正确的线程构造函数如下所示:
std::thread t1( &Sniffer::f1, this, y );
或者,您可以将 lambda 传递给线程构造函数:
std::thread t1([this, y] // capture the this pointer and y by value
{
this->f1(y);
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句