C++:回调函数
目录
- 1.定义:
- 2.示例:
1.定义:
回调函数:
- 是一种以函数指针作为参数的函数。这种函数可以在代码的其他部分被调用,从而实现一种类似高级编程语言中的“回调”机制。
注册回调函数:
- 是一种编程模式,它允许将代码(函数)作为参数传递给其他函数,并在特定事件发生后被调用。
.
2.示例:
String类型参数为例:
#include <iostream>
#include <string>// 定义一个函数指针类型,接受 std::string 参数
typedef void (*StringCallback)(const std::string&);// 具体的回调函数
void myStringCallback(const std::string& str) {std::cout << "Callback called with string: " << str << std::endl;
}// 使用回调函数的函数
void doSomethingWithString(StringCallback callback) {std::string value = "Hello, World!";callback(value); // 调用回调函数
}// main 调用
int main() {doSomethingWithString(myStringCallback); // 将myStringCallback函数作为参数传递return 0;
}
int多参数为例:
#include <stdio.h>// 定义回调函数的类型
typedef int (*Callback)(int, int);// 实现具体的回调函数
int add(int a, int b) {return a + b;
}int subtract(int a, int b) {return a - b;
}// 使用回调函数的函数
void useCallback(Callback cb, int a, int b) {int result = cb(a, b);printf("Result: %d\n", result);
}// ===================================================================
int main() {// 使用 add 函数作为回调useCallback(add, 5, 3);// 使用 subtract 函数作为回调useCallback(subtract, 5, 3);return 0;
}
.
声明:资源可能存在第三方来源,若有侵权请联系删除!