FunktionPointerArray in Singleton
FunktionPointerArray in Singleton
我尝试在拥有线程的单例中实现函数指针数组。在线程函数中,我收到一个错误,告诉我成员必须相对于对象。更多在评论行...
页眉:
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.
*/
}
}
相关文章:
- netcat command in c++
- Difference in displaying cv2 Mat
- C++ Singleton - Prevent ::instance() to variable
- C++ MFC Libraries in Travis CI
- 如何在OpenSSL中从configuration.h.in获取configuration.h
- 创建具有 new in 函数和"this is nullptr"异常的对象
- IN, OUT, INOUT Parameters
- 应用程序崩溃并显示"symbol _ZdlPvm, version Qt_5 not defined in file libQt5Core.so.5 with link time reference"
- 有人安装"IITB Simplecpp in mac"吗?
- 从 C 样式字符串中删除子字符串 "in place" 在C++代码中
- 如何修复"error: ‘_1’ was not declared in this scope"?
- Softmax Implementation in C++
- 将 out/in out 参数与 if/switch 的 init 语句一起使用
- IF-nesting in c++
- Gurobi GRBModel and GRBmodel in C++
- FunktionPointerArray in Singleton
- Singleton Service classes in c++
- Singleton in C++
- Error in Singleton
- Singleton in java vs. Singleton in C++