2011-10-15 31 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