我尝试在拥有线程的单例中实现函数指针数组。在线程函数中,我收到一个错误,告诉我成员必须相对于对象。更多在评论行...
页眉:
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;
};
身体:
#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){}
通过 getInstance 从 SingletonPattern 调用并不会让它变得更好。有什么建议吗?
ftnptr 是 Class 的成员。但是,您可以直接访问它。也就是说,pParent->*ftnptr[...] 表示"访问由指针 ftnptr[...]指定的 pParent 成员",但这并不意味着 ftnptr 也是 pParent 的成员。
正确的代码是 (pParent->*(pParent->ftnptr[...]))(...).但我建议从中提取数组索引表达式:
auto fnptr = pParent->ftnptr[...];
(pParent->*fnptr)(...);
我认为这可能是您声明指向成员函数的指针数组的方式。(编辑:这不是问题所在。无论如何,我都会保留这个答案,因为函数指针的 typedefs 确实可以使代码更清晰,所以我认为这是一个很好的建议。
尝试使用typedef
:
typedef void (Class::*ftnptr)(JOB Job);
ftnptr[2] fn_ptrs;
然后像这样使用它:
Class::Class(){
this->fn_ptrs[0] = &Class::ftn1;
this->fn_ptrs[1] = &Class::ftn2;
}
DWORD WINAPI Class::AutoplayerThreadFunction(LPVOID lpParam)
{
Class *pParent = static_cast<Class*>(lpParam);
while(true){
(pParent->*(pParent->fn_ptrs[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.
*/
}
}