这是我的 last question .我尝试改进我的类 Thread。 构造函数接收指向函数的指针,该函数必须在新线程中运行。
class Thread {
public:
Thread(void (*p)()) {
pf=p;
}
~Thread () {}
void StartThread() {
hThread = (HANDLE)_beginthreadex( NULL, 0, ThreadProc, NULL, 0, &threadID);
}
private:
void (*pf)();
HANDLE hThread;
unsigned threadID;
static unsigned WINAPI ThreadProc(LPVOID lpParam) {
(*pf)(); //error C2597 illegal reference to non-static member
return 0;
}
};
在 ThreadProc 中,我需要调用 TimerFunc。
void TimerFunc () {
i++;
}
这个类的使用示例:
Thread *timer;
timer = new Thread(TimerFunc);
timer->StartThread();
所以这是行不通的。 请有人告诉我,如果这个类是愚蠢的。 将指针发送到位于类外的 func 可能不是一个好主意? 谢谢你。
非常感谢您的建议! 现在可以了!
class Thread {
public:
Thread(void (*p)()) {
gg.pf=p;
}
~Thread ();
void StartThread() {
hThread = (HANDLE)_beginthreadex( NULL, 0, ThreadProc, this, 0, &threadID);
}
private:
struct mm {
Thread *pThread;
void (*pf)();
} gg;
HANDLE hThread;
unsigned threadID;
static unsigned WINAPI ThreadProc(LPVOID lpParam) {
mm hh;
hh.pThread=static_cast<Thread*> (lpParam);
hh.pf=hh.pThread->gg.pf;
hh.pf();
return 0;
}
};
你怎么看?这是正确的选择吗?
最佳答案
正如其他人所指出的,问题是静态方法不能访问非静态成员。执行此类操作的通常方法是将对象作为参数传递给线程启动例程,例如:
class Thread {
public:
Thread(void (*p)()) {
pf=p;
}
~Thread () {}
void StartThread() {
// Pass this as argument to ThreadProc
hThread = (HANDLE)_beginthreadex( NULL, 0, ThreadProc, this, 0, &threadID);
}
private:
void (*pf)();
HANDLE hThread;
unsigned threadID;
static unsigned WINAPI ThreadProc(LPVOID lpParam) {
// Get the passed Thread object
Thread *pThread = static_cast<Thread*> (lpParam);
pThread->pf();
return 0;
}
};
关于C++ 类 : pointer to a non-static func,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7499286/