回调函数(二)
实例一
typedef void (*MyFun)(int n, char* str);class Call{private:MyFun myFun;public:void SetFun(MyFun _myFun){myFun = _myFun; }void LetRun(int n, char* str) {myFun(n, str); } }; void Test(int n, char* str) //如果不定义全局变量,而定义在类中 则必须是 静态成员函数{while(n>0){cout<<n<<" "<<str<<endl;n--;}} int main(){ Call call;call.SetFun((MyFun)Test); //调回调函数的接口,并传入一个函数作为参数call.LetRun(10,"hello"); system("pause");return 0;}
实例二
#include <iostream>class AClass{public:void method1(){std::cout << "Method 1" << std::endl;}void method2(){std::cout << "Method 2" << std::endl;}};int main(){void (AClass::*Method)(void); AClass inst1;Method = &AClass::method1;(inst1.*Method)(); AClass* inst2 = new AClass;Method = &AClass::method2;(inst2->*Method)();delete inst2; system("pause");return 0;}