这可能是迟钝的,我已经搜索并尝试了很多解决方案,但我总是会出错。
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());
关于c++ - 无法通过函数指针c++执行类函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24231725/