您的位置:首页 > 其它

指向函数的指针--回调的基础

2014-12-20 23:23 295 查看
花了半天的时间研究回调函数,网上有些写得不对,所以记下备忘。

话说回来,,很久没有更新博客了,很多事貌似遗忘了。

#include<iostream>
using namespace std;

class callBackTest;
typedef void (callBackTest::*classfunp)(int a,int b,int &c);
typedef void (*generalfunp)(int a,int b,int &c);

class callBackTest
{
public:
callBackTest():value(0){}
~callBackTest(){}
int getValue(){return value;}

void func(classfunp callFun)
{
int a,b,c;
cout<<"class function input a:";
cin>>a;
cout<<"class function input b:";
cin>>b;
(this->*callFun)(a,b,c);
cout<<c<<endl;
}

void func(int input,classfunp callFun)
{
int a,b,c;
a=b=c=input;
(this->*callFun)(a,b,c);
}

void getABC(int a,int b,int &c)
{
value=c;
}

void test(int a,int b,int &c)
{
cout<<"test class function c=";
a=b=c=0;
}

static void s_test(int a,int b,int &c)
{
cout<<"test static class funciton c=";
a=b=c=0;
}

void sum(int a,int b,int &c)
{
cout<<"c=a+b=";
c=a+b;
}

void min(int a,int b,int &c)
{
cout<<"c=min(a,b)=";
c=a<b?a:b;
}

void max(int a,int b,int &c)
{
cout<<"c=max(a,b)=";
c=a<b?b:a;

}
private:
int value;
};

void func2(generalfunp callFun)
{
int a,b,c;
cout<<"general function input a:";
cin>>a;
cout<<"general function input b:";
(*callFun)(a,b,c);
cout<<c<<endl;
}

void test(int a,int b,int &c)
{
cout<<"test generalfunp c=";
a=b=c=0;
}

int main()
{
callBackTest cbt;

classfunp cp;
cp=&callBackTest::test;
cbt.func(cp);
cbt.func(&callBackTest::sum);
cbt.func(&callBackTest::max);
cbt.func(&callBackTest::min);
func2(callBackTest::s_test);
func2(callBackTest::s_test);
func2(test);
func2(&test);

///get value
cbt.func(12,&callBackTest::getABC);
int v=cbt.getValue();
cout<<v<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  回调函数