#include <iostream>
using namespace std;
typedef void (*FuncPtr)(void); //定义回调函数,定义一个函数参数为空,返回值为空的函数指针,参数和返回值形式都一样,但功能不确定的函数
class Test
{
public:
static void println(void) //作为参数的类成员函数必须声明为静态的
{
cout << "callback" << endl;
}
};
void FuncType(FuncPtr p)
{
cout << "FuncType" << endl;
p(); //调用回调函数
}
int main()
{
FuncType(Test::println); //不要带括号
return 0;
}输出:
FuncType
callback
本文介绍了一个使用C++实现的简单回调函数示例。通过定义一个类型为函数指针的变量并将其作为参数传递给另一个函数,在该函数内部调用这个函数指针所指向的函数来实现回调。示例中还演示了如何使用类成员函数作为回调函数。
3073

被折叠的 条评论
为什么被折叠?



