0

我尝试在拥有线程的单例中实现函数指针数组。在线程函数中我得到一个错误,告诉我一个成员必须是相对于一个对象。更多在评论区...

标题:

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){}

从 SingletonPattern 通过 getInstance 调用并没有让它变得更好。有什么建议么?

4

2 回答 2

1

ftnptr 是类的成员。但是,您可以直接访问它。也就是说,pParent->*ftnptr[...] 的意思是“访问由指针ftnptr[...] 指定的pParent 的成员”,但这并不意味着ftnptr 也是pParent 的成员。

正确的代码是 (pParent->*(pParent->ftnptr[...]))(...)。但我建议从中提取数组索引表达式:

auto fnptr = pParent->ftnptr[...];
(pParent->*fnptr)(...);
于 2012-10-13T15:58:26.517 回答
0

我认为这可能是您声明指向成员函数的数组的方式。(编辑:这不是问题所在。无论如何我都会保留这个答案,因为函数指针的类型定义确实可以使代码更清晰,所以我认为这是个好建议。)

尝试使用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.
    */
  }
}
于 2012-10-13T15:36:47.483 回答