#include <cstdio>void function(const char *text) {printf("%s", text);}int main(void) {void (*pfun)(const char *) = &function;(*pfun)("Hello, world.\n");return 0;}运行命令编译 lucky@lucky-macbook:cplusplus_callback_function$ g++ hello_world.cpp -o hello lucky@lucky-macbook:cplusplus_callback_function$ ./hello Hello, world.
二、函数式回调 1. 在c/c++允许函数指针作为函数参数传递 例如: void invoke_function(void (*callback_func)(parameter list)); 函数invoke_function的参数是函数指针callback_func,对于不熟悉c的开发者一开始会不习惯void (*callback_func)(parameter list)这种声明变量的方式。这样声明变量相当于 #typedef void (*CALLBACK_FUNCTION)(parameter list) CALLBACK_FUNCTION callback_func;
2. 简单的回调函数程序 function_callback.cpp =========================
#include <cstdio>编译并输出结果 lucky@lucky-macbook:cplusplus_callback_function$ g++ function_callback.cpp -o funcallback lucky@lucky-macbook:cplusplus_callback_function$ ./funcallback Hi, I'm lucky. Hi, I'm jacky, Nice to meet you. Just call me penny, I like football.
#include <cstring>
#define TEXT_LEN 128
/**定义函数lucky*/
void lucky(char *outName, size_t len) {
strncpy(outName, "Hi, I'm lucky.\n", len);
}
void jacky(char *outName, size_t len) {
strncpy(outName, "Hi, I'm jacky, Nice to meet you.\n", len);
}
void penny(char *outName, size_t len) {
strncpy(outName, "Just call me penny, I like football.\n", len);
}
void introduce(void (*person)(char *, size_t len)) {
char szText[TEXT_LEN] = {0};
(*person)(szText, TEXT_LEN);
printf("%s", szText);
}
typedef void (*FUNC_NAME)(char *, size_t);
int main(void) {
// 直接调用函数指针,注意使用了取地址符号&
introduce(&lucky);
// 直接定义变量方式使用函数指针
void (*pfun)(char *, size_t) = &jacky;
introduce(pfun);
// 先用typedef定义函数指针类型,再用改类型定义对应的函数指针变量,最后对变量赋值并传参调用
FUNC_NAME pfunc2 = &penny;
introduce(pfunc2);
return 0;
}