c++ - 在类中获取 "this"的上下文并分配给类指针 TheClass*

标签 c++ class pthreads

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 抛出错误的上下文。

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

最佳答案

我发现您的代码存在一些问题:

首先,static_cast<>需要 <> 中的类型, 和 this就像一个变量(所以不是一个类型)。 this 的类型是classe* (指向 classe 对象的指针)在 classe 内.

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

第三,pthread_create()假定一个自由函数(或静态成员函数)并且您提供一个类成员函数(classe::funct)。类成员函数需要一个对象才能工作(有点像隐式参数 == this )。你也没有 tclasse::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(); 
}

关于c++ - 在类中获取 "this"的上下文并分配给类指针 TheClass*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10038167/

相关文章:

c++ - C++ 中的宏/定义区分大小写吗?

c++ - 右值引用和完美转发

c - pthread_getschedparam 函数的奇怪行为

c - SMP 架构中的 pthread_create(3) 和内存同步保证

c++ - 未初始化的互斥锁超出范围——清理?

c++ - 使用 VS2012 编译 libffi 失败并出现 fatal error LNK1281 : Unable to generate SAFESEH image

c++ - 非菱形继承(钻石问题)树中的虚拟继承 - 内存和行为副作用

c++ - 在另一个类内存分配中创建一个类

java - 无法对非静态方法库进行静态引用

c++ - 未设置变量并返回异常数字