C++ PTHREAD 错误:非静态成员函数的使用无效
c++ pthread error: invalid use of non-static member function
我有错误:当我尝试编译以下代码时,非静态成员函数的使用无效:
int main()
{
data d;
cta ce;
pthread_t thread1;
pthread_t thread2;
pthread_create( &thread1, NULL, d.subscribe, NULL );
pthread_create( &thread2, NULL, ce.startStrategy, NULL );
pthread_join(thread1,NULL);
pthread_join(thread2,NULL);
return 0;
}
// cta.cpp
// ...
static void* cta::startStrategy()
{
std::cout<<"haha"<<std::endl;
}
// data.cpp
// ...
static void* data::subscribe()
{
std::cout<<"haha"<<std::endl;
}
收到错误:
main.cpp:38:52: error: invalid use of non-static member function
pthread_create( &thread1, NULL, d.subscribe, NULL );
^
main.cpp:39:60: error: invalid use of non-static member function
pthread_create( &thread2, NULL, ce.startStrategy, NULL );
但是,类似的代码片段效果很好:
#include <iostream>
#include <pthread.h>
class Foo {
public:
static void func() {
std::cout << "hi" << std::endl;
}
};
int main() {
Foo ins;
pthread_t pt;
pthread_t pt1;
pthread_create( &pt, NULL, ins.func, NULL );
pthread_create( &pt1, NULL, ins.func, NULL );
pthread_join(pt, NULL);
pthread_join(pt1, NULL);
return 0;
}
它编译得很好并打印了两次"嗨",我想知道我的代码可能出了什么问题,因为我已经从 void 更改为静态 void 并遵循相同的模式,为什么我仍然得到非静态错误?
首先,不要使用 pthread
。 用C++ std::thread
,成就幸福。
见证这一点:
std::thread t1(&data::subscribe, &d);
std::thread t2(&cta::start_strategy, &ce);
其次,问题最可能的原因是static
修饰符应该在类定义(.h 文件(中使用,而不是在类外的函数定义中使用。
如果你要使用pthread_create
,你必须向它传递它想要的参数。启动例程是 void *(*start_routine) (void *)
。请注意,其中没有任何关于任何成员函数的内容,无论是static
还是其他。因此,即使代码碰巧在某些平台上工作,代码也是不正确的。
相关文章:
- 为什么将值返回函数传递给重载=运算符对运算符函数有效,而对其他运算符无效
- 程序中的布尔函数返回输入的范围无论如何都是无效的
- 在这个函数中是有缺陷的,因为取消引用 null 是无效的,所以我想更改代码
- 在 Microsoft Access SQL 中调用自定义 DLL 函数时传递的内存地址无效
- C++无效的函数类型转换
- C++无效使用非静态成员函数?
- 模板和无效函数调用C++
- 控件到达非无效函数的末尾[-Wreturn类型]
- 获取控制权到达非无效函数警告的末尾,尽管我在 th 函数中有返回语句
- C++ 指针无效函数问题
- 为什么我总是得到 - 警告:控制达到非无效函数的末尾 [-Wreturn-type]
- 在无效函数中使用退出来纠正错误是否是一种好的做法
- 在C++ 通过按键进入和退出无效函数调用
- 指向指向无效函数参数的指针
- Xcode - 控制到达非无效函数运算符错误的末尾
- C++:对无效函数的未定义引用
- 二叉树无效函数
- 控件到达非无效函数的末尾
- 控件到达非无效函数的末尾
- 控制可能会到达非无效函数 xcode 的末尾