2011-10-15 28 views
6

我發現在調用C++成員函數指針和結構調用的指針信息,成員函數的指針,但我需要調用一個結構內部存在一個成員函數指針,我一直沒能得到正確的語法。我在MyClass類的方法中下面的代碼片段:調用C++從結構

void MyClass::run() { 
    struct { 
     int (MyClass::*command)(int a, int b); 
     int id; 
    } functionMap[] = { 
     {&MyClass::commandRead, 1}, 
     {&MyClass::commandWrite, 2}, 
    }; 

    (functionMap[0].MyClass::*command)(x, y); 
} 

int MyClass::commandRead(int a, int b) { 
    ... 
} 

int MyClass::commandWrite(int a, int b) { 
    ... 
} 

這給了我:

error: expected unqualified-id before '*' token 
error: 'command' was not declared in this scope 
(referring to the line '(functionMap[0].MyClass::*command)(x, y);') 

移動這些括號圍繞導致語法錯誤使用推薦*或 - > *兩者都不工作在這個情況下。有誰知道正確的語法?

+0

http://stackoverflow.com/questions/990625/c-function-pointer-class-member-to-non-static-member-function似乎與此相關的問題。 – Rudi

回答

8

用途:

(this->*functionMap[0].command)(x, y); 

測試和編譯;)

+0

啊完美!感謝回覆,上面的回答提供了推理。 – aaron

5

我還沒有編譯的任何代碼,而只是從看它,我可以看到你錯過了一些東西。

  • 從您調用函數指針的地方刪除MyClass::
  • 需要將this指針傳遞給函數(如果他們使用任何實例數據),這樣就意味着你需要的MyClass一個實例來調用它。

(後有點研究)它看起來像你需要做這樣的事情(也感謝@VoidStar):

(this->*(functionMap[0].command)(x, y)); 
+0

感謝您的解釋。下面的答案廠(括號包括「這個」而不是「functionMap」感謝您的答覆。 – aaron

+0

我不知道到底是否需要那些或沒有。雖然對於這個問題,我可能會嘗試不同的解決方案,比如只使用一個if,或者如果需要更多的靈活性,需要某種命令模式。 – Daemin