2014-04-02 87 views
0

這是一個回調函數的這部分,但我無法弄清楚這部分是如何工作的任何人都可以解釋我的代碼

如果(cb_onPress){cb_onPress(*此); } //觸發onPress事件

class Button; 
typedef void (*buttonEventHandler)(Button&); 

class Button { 
    public: 
//code 
    private: 
//code 
buttonEventHandler cb_onPress; 
}; 

void Button::process(void) 
{ 
    //code 
    if (cb_onPress) { cb_onPress(*this); } //fire the onPress event 

}  

void Button::pressHandler(buttonEventHandler handler) 
{ 
    cb_onPress = handler; 
} 

回答

2

cb_onPress是一個指向函數返回void並採取Button&參數。它可以指向是這樣的:

void foo(Button&){ std::cout << "Foo Button!\n"; } 

這條線,一個Button成員函數中,

if (cb_onPress) { cb_onPress(*this); } 

檢查該函數指針不爲空,如果是這樣,調用它,傳遞作爲參數的Button的相同實例(即通過*this達到的值)。使用的

實施例:

Button b; 
b.pressHandler(foo); // sets cb_onPress to point to foo 
.... 
b.process();   // Prints "Foo Button" 

雖然推測調用過程在內部發生,響應於正事件。

+0

對於我自己的啓示......它不應該是(* cb_onPress)(*此)嗎?我試了兩次,並沒有得到任何抱怨,因爲他們兩個都用g ++ – jsantander

+0

@jsantander AFAIK這兩個是相同的。我選擇較少的冗長選項。 – juanchopanza

1
if (cb_onPress) { cb_onPress(*this); } 

cb_onPress是指向一個功能。如果指針的一個nullptr你不能調用它,所以代碼檢查它不是事先。

整體支持客戶端使用是這樣的:

void myButtonEventHandler(Button& b) { ...do something when pressed... }; 

Button button; // make a button 
button.pressHandler(myButtonEventHandler); 
0

如果(cb_onPress)

檢查是否cb_onPress是空指針。換句話說,檢查之前是否定義了該功能。如果沒有,那麼它調用函數

cb_onPress

該對象

相關問題