假设我有一个课程,例如
class c {
// ...
void *print(void *){ cout << "Hello"; }
}
然后我有一个 c 向量
vector<c> classes; pthread_t t1;
classes.push_back(c());
classes.push_back(c());
现在,我想在 c.print();
以下是给我以下问题:
pthread_create(&t1, NULL, &c[0].print, NULL);
错误输出:无法将参数 ‘3’ 的 ‘void* (tree_item::*)(void*)’ 转换为 ‘void* (*)(void*)’ 到 ‘int pthread_create(pthread_t*, const pthread_attr_t*, void* (*)(无效*), 无效*)’
原文由 Angel.King.47 发布,翻译遵循 CC BY-SA 4.0 许可协议
您不能按照您编写的方式进行操作,因为 C++ 类成员函数有一个隐藏的
this
传入的参数pthread_create()
不知道this
的值---
使用,所以如果你试图通过将方法转换为适当类型的函数指针来绕过编译器,你会得到一个分段错误。您必须使用静态类方法(没有this
参数)或普通函数来引导类: