2012-07-21 114 views
0

我有這樣的代碼定義結構(傳入是簡單的結構)C++在陣列結構體的成員函數指針表示編譯錯誤

#define FUNCS_ARRAY 3 

    struct func 
    { 
     void (AA::*f) (incoming *); 
     int arg_length; 
    }; 

    func funcs[FUNCS_ARRAY]; 

然後在此類AA體我這樣定義指針數組:

funcs[0] = { &AA::func1, 4 }; 
funcs[1] = { &AA::func2, 10 }; 
funcs[2] = { &AA::func2, 4 }; 

當我嘗試經由所述陣列即時得到編譯錯誤調用的功能中的一個:
如果我這樣稱呼它(p是進入):

(*funcs[p->req]->*f)(p); 

即時得到這樣的錯誤:

error: no match for ‘operator*’ in ‘*((AA*)this)->AA::funcs[((int)p->AA::incoming::req)]’ 

當我嘗試調用它是這樣的:
(funcs中[對 - > REQ] - > * F)(對);
即時得到:

error: ‘f’ was not declared in this scope 

當我試試這個:

(funcs[p->req].f)(p); 

error: must use ‘.*’ or ‘->*’ to call pointer-to-member function in ‘((AA*)this)->AA::funcs[((int)p->AA::incoming::req)].AA::func::f (...)’, e.g. ‘(... ->* ((AA*)this)->AA::funcs[((int)p->AA::incoming::req)].AA::func::f) (...)’ 

什麼是訪問函數指針在側結構的正確方法?

+0

你可以使用['標準:: function'(http://en.cppreference.com/w/cpp/utility/functional/function)或[ 'boost :: function'](http://www.boost.org/libs/function/)來做所有的事情爲你包裝 – KillianDS 2012-07-21 14:35:31

回答

3

要通過指向成員函數來調用成員函數,您需要該指針和相應類的實例。

在你的情況下,指向成員的指針是funcs[i].f,我假設你有一個AA的實例,名爲aa。然後,你可以這樣調用該函數:

(aa.*(funcs[p->req].f))(p); 

如果aa是一個指針到AA,那麼語法是:

(aa->*(funcs[p->req].f))(p); 

如果你從內主叫(非的AA靜態)成員函數,然後嘗試:

(this->*(funcs[p->req].f))(p); 
+0

如果AA類中的方法在電話號碼的內部,那麼電話就是一個...... – user63898 2012-07-21 14:44:12

+0

在這種情況下使用'this'。 – Mat 2012-07-21 14:46:53

+0

我用過這個 - > *,謝謝! – user63898 2012-07-21 14:47:05