2012-11-30 162 views
2

可能重複:
How to best pass methods into methods of the same class類函數指針作爲參數

我從來沒有傳遞一個函數指針作爲參數的問題。這工作:

void functionThatTakesFPTR(void(*function)(int), int someValue){ 
    function(someValue); 
    } 

void printValue(int value){ 
    std::printf("%d",value); 
} 

int main(int argc, char** argv){ 
    functionThatTakesFPTR(&printValue, 8); 

    return EXIT_SUCCESS; 
} 

然而,通過目標函數不

void MyClass::setter(float value){ } 

void MyClass::testFunction(void(*setterPtr)(float)){ } 

void MyClass::someFunc(){ 
    testFunction(&(this->setter)); 
} 

對我來說,這看起來像傳遞的這個地址,而不是功能的,我有點糊塗了。是否有可能這樣做?並且是有可能通過另一個類(的實例MyClass2)的對象的函數指針?

編輯:錯誤我得到的是「class'MyClass'沒有成員'setter'」。

+0

http://www.parashift.com/c++-faq/pointers-to-members.html –

回答

6

的問題是,對一個方法的調用也需要對類實例的引用。你不能簡單地調用類方法,就像一個獨立的功能。

您需要閱讀關於Pointer-to-Member Functions

+5

你不能簡單地走進魔多。 – Yakk

+0

真棒!這非常有意義,現在。謝謝! – Mercurial