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
)。你也没有 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();
}
关于c++ - 在类中获取 "this"的上下文并分配给类指针 TheClass*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10038167/