class Child; class Parent { public: void (*funcPointer)(); void (*funcPointer2)(Parent* _this); void (Child::*funcPointer3)(); }; class Child: public Parent { public: void TestFunc(){ } void Do(){ Parent p; p.funcPointer=TestFunc; // error,'=': cannot convert from 'void (__thiscall Child::* )(void)' to 'void (__cdecl *)(void)' p.funcPointer2=TestFunc; // error too,'=': cannot convert from 'void (__thiscall Child::* )(void)' to 'void (__cdecl *)(Parent *)' p.funcPointer3=TestFunc; //this works p.funcPointer3=&Child::TestFunc; // this works too. p.funcPointer3(); // error,term does not evaluate to a function taking 0 arguments } };
解决方法
你不行您或者传递一个指向静态方法的指针,或者父级也必须接受一个指向该对象的指针.
你可能想看看boost::bind和boost::function:
#include <boost/bind.hpp> #include <boost/function.hpp> struct Y { void say(void) { std::cout << "hallo!";} boost::function<void()> getFunc() { return boost::bind(&Y::say,this); } }; struct X { //non-boost: void (Y::*func)(); Y* objectY; void callFunc() { (objectY->*func)(); } //boost version: boost::function<void()> f; }; X x; Y y; x.f = boost::bind(&Y::say,boost::ref(y)); x.f = y.getFunc(); x.f(); x.func = &Y::say; x.objectY = &y; x.callFunc();