2015-06-16 151 views
0

我試圖通過this指針作爲我的callback()的參數,但它看起來行爲與我所期望的不同。FLTK C++ Callbakc問題

我想通過調用者對象作爲我的user_data(即第二參數callback()),顯然它失敗了!

SaveSettings()方法,如果我type cast void*)obj to (SettingsGui*),並call foo(),其行爲與預期相同(所以,我能夠指針傳遞給調用SettingsGui obj?),但是當我試圖訪問vector<string> Order(這是SettingsGui::Show()方法中充滿了String對象),它失敗。

是我的「成功通過指針調用SettingsGui object」假設錯了嗎?如果是這樣,爲什麼,怎麼能解決呢?

// Gui for Application Settings 
class SettingsGui { 
    vector<string> Order; 
public: 
    const char foo() { return "Test"; } 

    void Show() { 
     ... 
     Order.size(); /* it is 44 here */ 
     ... 
     // Save Button 
     Fl_Button *SaveButton = new Fl_Button(...); 
     SaveButton->callback(SaveSettings, this); 
     ... 
    } 

    static void SaveSettings(Fl_Widget *w, void *d){ 
     SettingsGui *T = (SettingsGui*)obj; 
     fl_alert(T->foo()); /* this works */ 
     char buf[32]; 
     fl_alert(itoa(T->Order.size(),buf,10)); /* return -1 */ 

    } 
}; 

// Main Application Window 
class MainApp { 
public: 
    void Show(){ 
     ... 
     ... 
     Fl_Button *flButton_settings = new Fl_Button(...); 
     flButton_settings->callback(OpenSettingsGui); 
    } 

    static void OpenSettingsGui (Fl_Widget *w, void *d) { 
     SettingsGui p; 
     p.ReadSettings(...); 
     p.Show(); 
    } 
}; 

回答

1

T-> FOO()的作品,因爲它不能訪問任何機智hin類

T> Order.size()不起作用,因爲T正被轉換爲obj。它應該被轉換爲d。

static void SaveSettings(Fl_Widget *w, void *d){ 
    SettingsGui *T = (SettingsGui*)d;