2012-02-27 77 views
1

下面的示例使用函数指针指向类Blah的成员函数。函数指针的语法对我来说很清楚。然而,当打电话时,我不得不在this->*funcPtr左右放置括号,我不确定为什么这是必需的。我想这与C++如何评估表达式有关。所使用的编译器是VS 2008使用它的函数指针调用成员函数的C++语法

#include <iostream> 

using namespace std; 

struct Blah { 

    void myMethod(int i, int k) { 
     cout << "Hi from myMethod. Arguments: " << i << " " << k << endl; 
    } 

    typedef void (Blah::*blahFuncPtr)(int, int); 

    void travelSomething(blahFuncPtr funcPtr) { 
     (this->*funcPtr)(1, 2); 
     // w/o the brackets I get C2064 in VS 2008 
     // this->*funcPtr(1, 2); 
    } 
}; 

int main() { 
    Blah blah; 
    blah.travelSomething(&Blah::myMethod); 
    cin.get(); 
    return 0; 
} 
+1

http://www.parashift.com/c++-faq-lite/pointers-to-members.html#faq-33.6 – Mat 2012-02-27 06:54:03

+1

好的,也许一个宏是一个好主意。但是这仍然不能回答我的问题。我想知道为什么.. – Nils 2012-02-27 06:56:05

+0

呃以及如何定义一个指向函数的指针宏,例如使用可变宏来引用参数? – Nils 2012-02-27 07:06:35

回答

2

的函数调用操作()需要优先级数字比“指针构件”操作符->*

例如参见here

+0

呃这很简单,thx的答案。 – Nils 2012-02-27 07:02:41