非静态成员函数c++线程linux的无效使用

达克瓦米尔

我尝试运行一个函数,它启动线程,但我收到错误:

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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Linux-信号:错误:无效使用非静态成员函数

如何使用非静态成员函数作为模板参数?

无效使用非静态成员函数

Arduino错误(C ++):无效使用非静态数据成员

C ++ 11:使用非静态成员函数作为类构造函数中的默认参数

无效使用非静态成员函数C ++

线程错误:无效使用非静态成员函数

C ++ freeRTOS任务,无效使用非静态成员函数

错误:ISO C ++禁止使用不合格或带括号的非静态成员函数的地址形成指向成员函数的指针

在头文件中无效使用非静态成员函数

将成员函数作为函数变量传递时,无效使用非静态成员函数C ++

将ino sketch转换为C ++类,无效使用非静态成员函数

为什么会有一个额外的&来将非静态成员函数的地址传递给C ++中的线程?

C ++使用模板类调用非静态成员函数

CC_SYNTHESIZE(int,beadColor,_BeadColor); 在非静态成员函数外部无效使用“ this”

使用C ++非静态成员函数的C回调函数的问题

使用C ++非静态成员函数作为回调和类范围问题

boost :: thread无效使用非静态成员函数

C ++无效使用非静态数据成员

使用std :: function包装非静态成员函数指针

我使用C ++引用函数或数据成员吗?(必须调用对非静态成员函数的引用)

pthread_create-无效使用非静态成员函数

无效使用非静态成员函数-类成员函数调用另一个类成员函数

错误:无效使用非静态成员

错误:非静态成员函数 C++ 的无效使用

如何设置 (*sa_handler)(int) 指向作为类成员的函数的指针?(非静态成员函数的无效使用)

错误:在 C++ 中无效使用非静态成员函数

非静态成员函数 int test::funcAB(int, int) 的无效使用

c ++ 17 错误消息:在向量上使用宏时“必须调用对非静态成员函数的引用”