2012-10-13 29 views
0

我嘗試在擁有一個線程的單例中實現一個函數指針數組。 在線程函數中,我得到一個錯誤,告訴我一個成員必須是相對於一個對象的。更多的commentline ...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犯規呼叫使它更好。 有什麼建議嗎?

+0

這是一個分組問題嗎?嘗試'(pParent - > *(ftnptr [...]))'。 –

+0

沒有。原因似乎隱藏在其他地方。我有這個:「(this - > * internalUpdate)(hWnd);」代碼中的其他地方。它的工作正常。 – ManuelSchneid3r

+0

我特指的是方括號的分組。你的反例是不恰當的,因爲它沒有這些。 –

回答

1

ftnptr是類的一個成員。但是,您可以直接訪問它。也就是說,pParent - > * ftnptr [...]的意思是「訪問由指針ftnptr [...]指定的pParent成員」,但並不意味着ftnptr也是pParent的成員。

正確的代碼(pParent - > *(pParent-> ftnptr [...]))...(...)。但我會建議從中提取數組索引表達式:

auto fnptr = pParent->ftnptr[...]; 
(pParent->*fnptr)(...); 
+0

可怕但卻像魅力一樣工作。 – ManuelSchneid3r

0

我想這可能是你如何聲明你的指針到成員函數的數組。 (編輯:這不是什麼錯誤,我仍然保持這個答案,因爲函數指針的typedef確實可以使代碼更乾淨,所以我認爲這是個好建議。)

嘗試使用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. 
    */ 
    } 
} 
+0

對不起,Stackoverflow因維護而關閉。我沒有測試它。但在閱讀上面的anwser後,我認爲它不會工作。無論如何感謝您的努力。 – ManuelSchneid3r

+0

我很確定'typedef'可以工作。但是,它不能解決其他答案指出的問題:試圖通過函數指針取消引用對象的成員。爲了讓我的答案有效,你必須做出同樣的改變。 –

+0

我添加了使上述代碼正確的代碼。對函數指針使用'typedef'確實可以使代碼更清晰,所以我會強烈推薦它。 –