2016-10-26 86 views
0

我想调用一个方法初始化指针到其他类的方法,我遵循this: 但它没有为我工作。通过指针非静态初始化的调用类方法

这样考虑:

class y 
{ 
    public: 
     int GetValue(int z) 
     { 
      return 4 * z; 
     } 
}; 


class hooky 
{ 
    public:  
     int(hooky::*HookGetValue)(int); 
}; 


int(hooky::*HookGetValue)(int) = (int(hooky::*)(int))0x0; // memory address or &y::GetValue; 



int main() 
{ 
    hooky h; // instance 
    cout << h.*HookGetValue(4) << endl; // error 
    return 0; 
} 

产生是误差:

[错误]必须使用”。 '或' - >',以调用 'HookGetValue(...)'中的指向成员函数,例如, '(... - > * HookGetValue)(...)'

+1

'(H * HookGetValue)(4)'呢? –

+0

@AdrianShum非常感谢,但为什么有用?请你可以告诉我吗?,我不明白是否一样。 – nikomaster

+1

检查我的更新 –

回答

1

正确的语法来调用一个成员函数指针是

(h.*HookGetValue)(4) 

更新:原因原来的代码不按预期工作是因为C++的运算符优先级:函数调用()比成员.*的ptr具有更高的优先级。这意味着

h.*HookGetValue(4) 

将我猜你应该写看到的

h.*(HookGetValue(4))