2016-06-21 102 views
0

我有一個包含兩個相似的非靜態函數的類,我想分配上飛他們中的一個函數指針:C++的Arduino:一個函數分配給函數指針

啊:

class A{ 
    private: 
    void (*funcPtr)(int); 
    void do_sth(int i); 
    void do_sth_else(int i); 
} 

A.cpp:

A::A(int i){ 
    if(i == 1) 
     A::funcPtr = A::do_sth; // or &A::do_sth; 
    else 
     A::funcPtr = A::do_sth_else; // or &A::do_sth_else; 
} 

,但我得到這樣的錯誤:

error: cannot convert 'A::do_sth' from type 'void (A::)(int)' to type 'void (*)(int)' 

我讀了多個類似的問題,但不能將他們的解決方案應用於我的問題。

+0

考慮到Arduino的內存限制,函數指針可能有點過於複雜。如果編譯器可以處理它,爲什麼不使用[lambda](http://stackoverflow.com/questions/24352785/c-closure-to-pass-member-function-as-normal-function-pointer)? –

回答

1

這些是成員函數。通過使用類名限定它,可以使funcPtr成爲一個成員指針,或者使do_sth(),do_sth_else()爲靜態成員函數。我建議在獲取地址時在函數名前面使用&