回调函数——使用typedef(转)

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

date: 20180811

回调函数:就是一个通过函数指针调用的函数。如果你把函数的指针作为参数传递给另外一个函数,档这个指针被用来调用其指向的函数时,我们就说这是回调函数。回调函数不是由该函数的实现方直接调用,而是在特定的事件或条件发生时由另外的一个调用,用于对该事件或条件进行的响应。

函数指针:

返回值 (*函数名)(参数列表);

如:int (*callback)(int i);

1. typedef定义函数指针类型

#include <iostream>

using namespace std;

typedef int (*fp)(char c);

int f0 (char c) { cout << "f0, c= " << c << endl; return 0; };
int f1 (char c) { cout << "f1, c= " << c << endl; return -1; };

int main ()
{
    fp Fp;
    Fp = f0;
    cout << Fp ('a') << endl;
    system ("pause");
    Fp = f1;
    cout << Fp ('b') << endl;
    system ("pause");

    return 0;
}

输出:

2. typedef定义函数类型

#include <iostream>

using namespace std;

typedef int f(char c);

int f0 (char c) { cout << "f0, c= " << c << endl; return 0; };
int f1 (char c) { cout << "f1, c= " << c << endl; return -1; };

int main ()
{
    f *Fp;
    Fp = f0;
    cout << Fp ('a') << endl;
    system ("pause");
    Fp = f1;
    cout << Fp ('b') << endl;
    system ("pause");

    return 0;
}

 输出:

——————————————————————

回调函数有什么作用呢?

1. 回调函数就是由用户自己做主的函数:

比如,OnTimer()定时器的回调函数,当时间到了需要做什么完全交给用户自己处理

2. 回调函数很有可能是输入输出的一种方式:

对于DLL来说,函数的参数由输入参数,输出参数。回调函数的指针作为其参数的话,可以起到输入的作用。当然,也可以起到输出的作用。

通过回调函数,可以一次又一次频繁的传递值——比如视频流。

3. 回调函数里面的实现,仍然可以是回调函数。

总之,回调函数的作用:

>. 决定权交给客户端

>. 与客户端进行交流

>. 通过客户端进行输入

>. 通过客户端进行输出

实例:

#include <iostream>

using namespace std;

typedef int (*CallbackFun)( char *p_ch );

int AFun (char *p_ch)
{
    cout << "Afun 回调:	" << p_ch << endl;
    return 0;
}

int BFun (char *p_ch)
{
    cout << "BFun 回调:	" << p_ch << endl;
    return 0;
}

int Call (CallbackFun p_Callback, char *p_ch)
{
    cout << "call 直接打印出字符:	" << p_ch << endl;
    p_Callback (p_ch);
    return 0;
}

int Call2 (char *p_ch, int (*pfun)(char *))
{
    cout << "通过指针方式执行回调函数。。。" << endl;
    ( *pfun )( p_ch );
    return 0;
}

int Call3 (char *p_ch, CallbackFun p_Callback)
{
    cout << "通过命名方式执行回调函数。。。" << endl;
    p_Callback (p_ch);
    return 0;
}

int main ()
{
    char *p_ch = "Hello world!";
    Call (AFun, p_ch);
    Call (BFun, p_ch);

    Call2 (p_ch, AFun);

    Call3 (p_ch, AFun);
    system ("pause");

    return 0;
}

输出:

——————————————————————

原文地址:https://www.cnblogs.com/xiawuhao2013/p/9459911.html