0
class classe (){
public: 
    int key;

    static void *funct(void *context){
        printf("Output: %d, ", key);
    }

    void Go(){
        classe c = static_cast<this>(context); //<- This doesn't work, Context of this-> goes here
        pthread_create(&t, NULL, &classe::funct, c);
    }
};

int main(){

    classe c;
    c.key = 15;
    c.Go();

    c.key = 18;
    c.Go();
}

输出应该是Output: 15, Output: 18,,事情是获取this抛出错误的上下文。

有人知道如何解决这个问题吗?

4

4 回答 4

2

我可以看到您的代码存在一些问题:

首先,static_cast<>需要 , 中的类型<>,并且this像变量一样(所以不是类型)。的类型thisclasse*(指向classe对象的指针)内classe

其次,没有context可用的classe:Go()。该名称有一个参数classe::fuct(),但在您想使用它的地方不可用。

第三,pthread_create()假设一个自由函数(或静态成员函数)并且您提供了一个类成员函数(classe::funct)。类成员函数需要一个对象才能工作(有点像隐式参数 == this)。您也没有可以传递给的t定义classe::Go()pthread_create()

你可以试试:

static void *funct(void *key){ // funct is now a free function, all data is provided to it
    printf("Output: %d, ", *static_cast<int*>(key)); 
} 

class classe ()
{ 
public:  
  int key; 

  void Go(){
    pthread t; 
    pthread_create(&t, NULL, funct, &key); // pass (address of) key to funct
  } 
}; 

int main(){ 

  classe c; 
  c.key = 15; 
  c.Go(); 

  c.key = 18; 
  c.Go(); 
}
于 2012-04-06T01:38:48.933 回答
1

首先,您需要在context某个地方定义。其次,this是一个关键字,表示指向正在调用成员函数的对象的指针。static_cast在模板参数中需要一个类型。替换static_cast<this>static_cast<classe*>, 并将类型更改为cclasse *使语句编译。

于 2012-04-06T01:36:06.320 回答
1

尝试这样的事情:

#include <stdio.h>
#include <pthread.h>

class classe
{
public: 
    int key;

    static void* funct(void *context)
    {
        classe* c = static_cast<classe*>(context);
        printf("Output: %d, ", c->key);
        return context;
    }

    void Go()
    {
        pthread_t t;
        pthread_create(&t, NULL, &classe::funct, this);
        void* p = 0;
        pthread_join(t, &p);
    }
};

int main()
{
    classe c;
    c.key = 15;
    c.Go();

    c.key = 18;
    c.Go();
    return 0;
}

我将使用上下文移动到正确的函数,并添加了 pthread_join 以便程序在线程有机会运行之前不会退出。

于 2012-04-06T01:57:13.120 回答
0

您似乎对某些关键部分的去向感到有些困惑。这是一个粗略的骨架,我认为它可以满足您的大部分需求。

class classe {
    public:
        classe(int k) : key(k) { }

        void Go() {
            // where does "t" come from?
            pthread_create(&t, NULL, &funct, static_cast<void*>(this));
        }

    private:
        int key;

        static void* funct(void* context) {
            classe* self = static_cast<classe*>(context);
            printf("Output: %d ", self->key);
            return 0; // not sure this is what you want
        }
};

int main() {
    classe c(15);
    c.Go();
}
于 2012-04-06T01:50:02.963 回答