我尝试在拥有线程的单例中实现函数指针数组。
在线程函数中,我得到一个错误,告诉我成员必须相对于对象。评论行中的更多内容...
header :
typedef struct{
int action;
HWND handle;
}JOB;
class Class{
public:
enum Action { 1,2 };
private:
JOB m_currentJob;
queue<JOB> Jobs;
static DWORD WINAPI ThreadFunction(LPVOID lpParam);
void (Class::*ftnptr[2])(JOB Job);
void Class::ftn1(JOB Job);
void Class::ftn2(JOB Job);
// Singleton pattern
public:
static Class* getInstance(){
if(sInstance == NULL)
sInstance = new Class();
return sInstance;
}
private:
Class(void);
~Class(void);
static Class* sInstance;
};
body :
#include "Class.h"
Class* Class::sInstance = NULL;
Class::Class(){
this->ftnptr[0] = &Class::ftn1;
this->ftnptr[1] = &Class::ftn2;
}
DWORD WINAPI Class::AutoplayerThreadFunction(LPVOID lpParam)
{
Class *pParent = static_cast<Class*>(lpParam);
while(true){
(pParent->*ftnptr[pParent->m_currentJob.action])(pParent->m_currentJob);
/* The line above causes the compiler error. Curious to me is that
* neither "pParent->m_currentJob" nor "pParent->m_currentJob" cause
* any problems, although they are members too like the ftnptr array.
*/
}
}
void Class::ftn1(JOB Job){}
void Class::ftn2(JOB Job){}
从SingletonPattern通过getInstance进行的调用并没有使它变得更好。
有什么建议?
最佳答案
ftnptr是Class的成员。但是,您直接访问它。也就是说,pParent-> * ftnptr [...]的意思是“访问由指针ftnptr [...]指定的pParent的成员”,但这并不意味着ftnptr也是pParent的成员。
正确的代码是(pParent-> *(pParent-> ftnptr [...]))(...)。但是我建议从中提取数组索引表达式:
auto fnptr = pParent->ftnptr[...];
(pParent->*fnptr)(...);