静态线程函数访问非静态类成员在C++
Class Test{
int value;
static void* thread_func(void* args){
value++;
}
void newthread(){
pthread_create(&thread_func,...);
}
}
我试图创建Class Test.
因此编译器会强迫一个线程我做thread_func
静态的。但是,我无法再访问非静态成员“value
”。它说:静态线程函数访问非静态类成员在C++
invalid use of member 'Class::value' in static member function
有没有办法解决它?
但是我不能访问非静态 成员“值”了。
那是因为在你的类static
功能没有(和不能有)this
指针。所有你需要的指针传递给Test
对象pthread_create()功能第四参数,然后做到这一点:
static void* thread_func(void* args)
{
Test *test = static_cast<Test*>(args);
test->value++;
//write return statement properly
}
但是,如果你正在做的thread_func()
太多的事情需要访问在很多地方Test
类的成员,那么我建议这样的设计:
//this design simplifies the syntax to access the class members!
class Test
{
//code omitted for brevity
static void* thread_func(void* args)
{
Test *test = static_cast<Test*>(args);
test->run(); //call the member function!
//write return statement properly
}
void run() //define a member function to run the thread!
{
value++;//now you can do this, because it is same as 'this->value++;
//you do have 'this' pointer here, as usual;
//so access other members like 'value++'.
}
//code omitted for brevity
}
更好的设计:定义一个可重用的类!
甚至更好的是定义与纯虚拟函数run()
一个可重复使用的类由派生类来实现。这是它应该如何设计:
//runnable is reusable class. All thread classes must derive from it!
class runnable
{
public:
virtual ~runnable() {}
static void run_thread(void *args)
{
runnable *prunnable = static_cast<runnable*>(args);
prunnable->run();
}
protected:
virtual void run() = 0; //derived class must implement this!
};
class Test : public runnable //derived from runnable!
{
public:
void newthread()
{
//note &runnable::run_thread
pthread_create(&runnable::run_thread,..., this);
}
protected:
void run() //implementing the virtual function!
{
value++; // your thread function!
}
}
看起来更好?
让thread_func将一个指向该类的对象的指针作为参数。
static void* thread_func(void* pThis)
{
static_cast<Test*>(pThis)->value++;
}
在的情况下,这种方法要采取一些其他的信息,以及,把双方在另一个struct/class
和传递英寸
指向对象的指针。 C++在运行时不存在类,因此不能有指向类的指针。 – 2011-01-08 11:17:32
谢谢。编辑。 – 341008 2011-01-08 13:20:44
我已更新我的帖子。一探究竟! – Nawaz 2011-01-09 00:18:56