[英]Can't execute a class function through a function pointer c++
這可能會受阻,我已經搜索並嘗試了許多解決方案,但是我總是會出錯。
class mainStateMachine;
typedef void (mainStateMachine::*StateProc)( EIndication input);
class mainStateMachine
{
public:
StateProc currentState;
int transition;
void rotateUntilBlobsFound ( EIndication input);
void clarifyImage (EIndication input);
}
接着:
main()
{
int input=0;
StateProc BLA;
mainStateMachine mainMachine;
mainMachine.currentState=&mainStateMachine::rotateUntilBlobsFound;
BLA=mainMachine.currentState;
BLA(input);
}
由於某種原因,這不起作用,告訴我“必須使用'。 '或'-> '來調用'BLA(...)中的成員指針函數”,即使我執行* BLA(input); 它不起作用。 我真的不明白為什么這行不通。
BLA需要一個指向實例的指針,因為成員函數指針本身不能直接取消引用(調用了其函數)。 必須代表某個對象調用它們,然后該對象提供成員函數使用的“ this”指針。 如果函數不知道在哪個對象上操作,您還可以怎么做才能影響對象實現。
因此,這是調用分配給BLA的方法的方式:
(mainMachine.*BLA)( input);
您還可以考慮使用boost::function
或std::function
代替原始指針來簡化操作,例如:
std::function< void(const mainStateMachine&, EIndication)> f_ptr =
&mainMachine::rotateUntilBlobsFound;
const mainStateMachine foo;
f_ptr( foo, EIndication());
除了其他錯誤外,例如在類定義后沒有分號並且在main
上沒有返回類型,指向成員的指針需要一個對象來進行操作。 您可以使用指向成員運算符的指針來提供一個:
(mainMachine.*BLA)(input);
作為指向成員函數的指針,所有BLA
包含的都是成員函數的地址,而不是與其一起使用的任何對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.