#include <iostream>
#include <unistd.h>
using namespace std;
//类型别名,A是void(*A)()的函数指针,,以后A是一种类型
typedef void(*A)();
typedef void(*B)(string s);
//如:可以声明函数指针callback
A callback;
//typedef另一种用法
typedef int I;
I a = 1;
I x = 2;
//c11新用法
using in = int;
in in1 = 1;
in in2 = 2;
void callback_fun()
{
cout << "吃虾" << endl;
}
void callback_fun2(string s)
{
cout << s << endl;
}
void fun( int a, A b)
{
for(int i =0;i<a;i++)
{
//直接使用函数指针,调用该函数
b();
//等价于,先解引用指针,再调用函数
(*b)();
}
cout << "callback:()" <<endl;
}
//看起来是传入函数,实际上形参传入函数或数组,此时都转化为指针
void fun2( int a, B callback)
{
for(int i =0;i<a;i++)
{
//直接使用函数指针,调用该函数
(*callback)("callback:(string)");
}
}
int main()
{
fun(2,callback_fun);
//把函数名作为值使用时,该函数名自动转换成指针
fun2(2,callback_fun2);
cout << "Hello World!" << endl;
return 0;
}
C++可调用对象:回调函数
最新推荐文章于 2024-05-10 16:35:55 发布