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

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

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include         /* 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;
}

你可能感兴趣的:(C/C++,c++)