参考
深入理解:回调函数_极客点儿的博客-CSDN博客_回调函数
回调函数 - doitjust - 博客园
举个例子吧,主函数所在源文件假如叫主模块,主函数所在源文件中调用的其他函数所在的源文件叫子模块。正常调用函数的过程是主模块调用子模块的函数,如果有一种函数在子模块调用主模块的函数,那么这种函数就叫做回头调用,即回调函数。
你到一个商店买东西,刚好你要的东西没有货,于是你在店员那里留下了你的电话,过了几天店里有货了,店员就打了你的电话,然后你接到电话后就到店里去取了货。
或者是说,你的电话号码就叫回调函数,你把电话留给店员就叫登记回调函数,店里后来有货了+店员给你打电话叫做 触发回调事件,你到店里去取货这个动作叫做 响应回调事件。你拿到货叫做程序执行结果,于此同时显示出调用回调函数(你的电话号码)的作用。
代码示例
para_callback.h
#ifndef __PARA_CALLBACK_H #define __PARA_CALLBACK_H typedef void(*callback_t)(void *); void repeat_three_times(callback_t f, void *para); #endif#pragma once
para_callback.cpp
#include "para_callback.h"
void repeat_three_times(callback_t f, void *para)
{
f(para);
f(para);
f(para);
}
main.cpp
#include#include "para_callback.h" #include //using namespace std; void say_hello(void *str) { printf("Hello %srn", (const char *)str); } void count_numbers(void *num) { int i = 0; for (i = 1; i <= (int)num; i++) { printf("%d ", i); } putchar('n'); } //void * string1 = "Guys"; int main(void) { repeat_three_times(say_hello, "Guys"); repeat_three_times(count_numbers, (void *)4); return 0; }
运行上面这个程序可能会出现以下错误
严重性 代码 说明 项目 文件 行 禁止显示状态 错误 C2664 “void repeat_three_times(callback_t,void *)”: 无法将参数 2 从“const char [5]”转换为“void *” Project2 d:filevs_projectproject2project2main.cpp 23
严重性 代码 说明 项目 文件 行 禁止显示状态 错误 C2440 “初始化”: 无法从“const char [5]”转换为“void *” Project2 d:filevs_projectproject2project2main.cpp 24
参考下面这个博客
vs2017 :C2440 错误,无法从 const char[] 转换为 char*问题解决_皮卡橘橘的博客-CSDN博客
项目属性配置->C/C++ -> 语言 -> 符合模式,从“是/permissive”改为“否”。



