c++ 调用pthread_create函数时,传入类中的成员报错。解决方法。

1.问题出现

我想把我的c程序转成c++的方式写,因为我觉得c++的面向对象方式特别的好用。

然后我开始移植了,当我想把在一个类函数中调用pthread_create来创建一个类。

我给的参数是

s=pthread_create(&id,NULL,run,NULL);


//函数原型

void * THREAD_433::run(void *arg)
{
    void * ret;
    using namespace  std;
    cout<<"hello!\r\n";
    return ret;
}

这个时候就会编译出错,

D:\Cprogress\pthread\my_thread.cpp:15: error: cannot convert 'THREAD_433::run' from type 'void* (THREAD_433::)(void*)' to type 'void* (*)(void*)'
     s=pthread_create(&id,NULL,run,NULL);
                                       ^

他说这个类型不匹配。

2.问题解决

出现类型不匹配的问题。因为pthread_create需要的参数类型为void* (*)(void*),而run作为类的成 员函数时其类型是void* (Thread_433::)(void*)的成员函数指针。

我们知道类的成员函数在经过编译器处理之后,会变成带有 this指针参数的全局函数,所以类型注定是不会匹配的。

但是如果将run声明为static类型,那么编译器会将static形式的函数,转换成不带this指针的全局函数,所以其类型可以与pthread_create需要的参数类型相匹配。但是类的静态成员函数无法访问类的非静态成员,不过这可以通过传递this指针解决这个问题。

修改过的代码:其他都不需要变

void THREAD_433::Init(void)
{

    int s;
    s=pthread_create(&id,NULL,THREAD_433::run,NULL);
    if(s!=0)
            std::cout<<"err!\r\n";
}


/**********类声明***********/
class THREAD_433
{
public:
    THREAD_433 ();
    void Init(void);
    void Delete(void);

private:
    pthread_t id;
    static void *run(void *arg);
};

猜你喜欢

转载自www.cnblogs.com/ZQQH/p/8930193.html