2016-10-26 87 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))