c++ error: invalid use of non-static member function

      在把一个C代码的编码示例代码封装成一个C++的类,其中涉及到类函数创建一个进程,进程处理函数据是本类的方法函数,遇到了无效使用非静态成员函数的报错。用以下方法解决了报错,同事说还可以用单例模式来解决。

#include <atomic>
#include <chrono>
#include <iostream>
#include <string>
#include <sys/epoll.h>
#include <thread>
#include <vector>
#include <dirent.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>        /* read */

using namespace std;

class AcEncoder
{
    public:
        void StreamingLoop( int x );
        void EncoderYUV();
};

void AcEncoder::StreamingLoop( int x )
{
    while (true)
    {
        sleep(x);
        std::cout << "yuv->h264" << std::endl;
    }
}

void AcEncoder::EncoderYUV()
{
    int second = 2;

    /*
     * error: invalid use of non-static member function ‘void AcEncoder::StreamingLoop(int)’
     * 无效使用非静态成员函数
     *
     * 报错原因:因为没有类对象,也就是没有类的实例化
     */

    // std::thread enc1( StreamingLoop, second );     /* error */
                                
    /*
     * 在 C++ 中,成员函数有一个隐含的第一个参数绑定(bind)到 this。创建线程时,必须传递this指针。
     * 还必须使用类名来限定成员函数。
     *
     * 这种情况下正确的线程构造函数如下所示:
     */
    
    std::thread enc1( &AcEncoder::StreamingLoop, this, second );


    /*
     * 也可以将 lambda 传递给线程构造函数:
     */
    std::thread enc2([this, second] // capture the this pointer and second by value
    {
        this->StreamingLoop(second);
    });

    enc1.join();
    enc2.join();
}

int main()
{
    AcEncoder en;

    en.EncoderYUV();

    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值