C++小技巧---回调函数的使用
·
C++中的回调函数(Callback Function)是一种通过将函数作为参数传递给另一个函数来实现某些操作的机制。回调函数常用于事件驱动编程、异步操作、库的接口设计等场景。
在C++中回调函数的使用有三种方式:
方法1:使用函数指针进行回调函数的定义。
方法2:使用std::function进行回调函数的定义,std::function是一个模板类,可以指定返回值类型和参数类型,可以方便地定义回调函数。
方法3:使用函数对象来实现回调函数的定义,函数对象是一个类,可以重载()运算符,可以方便地定义回调函数。
代码示例:
#include <iostream>
#include <string>
#include <functional>
using namespace std;
//方法1:使用函数指针进行回调函数的定义
typedef string (*MyCallback)(string str1,string str2);
//方法2:使用std::function进行回调函数的定义,std::function是一个模板类,可以指定返回值类型和参数类型,可以方便地定义回调函数.
typedef std::function<string(string, string)> MyFunCallbackFun;
//方法3:使用函数对象来实现回调函数的定义,函数对象是一个类,可以重载()运算符,可以方便地定义回调函数.
class funObject{
public:
funObject() {}
~funObject() {}
string operator() (string str1, string str2) {
cout << "使用函数对象进行回调函数的定义:" << str1 << " " << str2 << endl;
return str1 + str2;
}
};
string MyCallBackFun1(string str1, string str2) {
cout << "使用函数对象进行回调函数的定义:" << str1 << " " << str2 << endl;
return str1 + str2;
}
string MyCallBackFun2(string str1, string str2) {
cout << "使用std::function进行回调函数的定义:"<< str1 << " " << str2 << endl;
return str1 + " " + str2;
}
//回调函数的定义
void CallBack(MyCallback callback, string str1, string str2) {
string result = callback(str1, str2);
cout << "CallBack 回调函数的返回值:" << result << endl;
}
void CallBackFun(MyFunCallbackFun callback, string str1, string str2) {
string result = callback(str1, str2);
cout << "CallBackFun 回调函数的返回值:" << result << endl;
}
void CallObject(funObject callback, string str1, string str2) {
string result = callback(str1, str2);
cout << "CallObject 回调函数的返回值:" << result << endl;
}
//主函数
int main() {
MyCallback backFun = MyCallBackFun1; //使用函数指针进行回调函数的定义
MyFunCallbackFun backFun2 = MyCallBackFun2; //使用std::function进行回调函数的定义
cout << "===============================================" << endl;
CallBackFun(backFun, "Hello", "World");
cout << "===============================================" << endl;
CallBackFun(backFun2, "Hello", "World");
funObject objectFun;
cout << "===============================================" << endl;
CallObject(objectFun, "Hello", "World");
return 1;
}
更多推荐

所有评论(0)