回调函数概念
利用程序通过参数把该函数的函数指针传递给其他的函数,在那个函数里调用这个函数指针就相当于调用这个函数,这样的过程就叫回调,而被调用的函数就叫回调函数。回调函数的本质是利用函数指针传递,要理解回调机制,就要先学习函数指针。
函数指针概念
函数指针就是指向函数的指针,指向某一种特定的类型。函数的类型由它的返回类型和形参类型共同决定,与函数名无关。例如:
bool SpawnProduct(const string&);
如何声明一个指向该函数的指针,只需要将函数名字替换成指针即可,如下
bool (*ptr) (const string&); // ptr 就是一个函数指针
把函数名作为一个值使用时,该函数自动地转换成指针,比如把SpawnProduct的地址赋给ptr,如下
ptr = SpawnProduct;
ptr = &SpawnProduct;
使用typedef定义函数指针类型
typedef bool func(const string&, const string&); // 函数类型
typedef bool (*ptr) (const string&,const string&); // 指针类型
实例如下:
#include <iostream>
// 函数指针
typedef bool (*ptr)(const string);
// 指针指向的函数(或者称为回调函数)
bool SpawnProduct(const string name)
{
if (name == "hello")
{
return true;
}
else
return false;
}
int main()
{
ptr p_function = SpawnProduct;
cout<< (*p_function)("h")<<endl;
}