回调函数最简单用法
// CallBackFunc.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <string>
using namespace std;
string toZeroDown(int n, void *contex) {
cout << "toZeroDown:" << -*(int*)(contex) << endl;
return "toZeroDown";
}
string toZeroUp(int n, void *contex) {
cout << "toZeroUp:" << *(int*)(contex) << endl;
return "toZeroUp";
}
typedef string(*CallBackFunc)(int n, void *contex);
void registNumCallBack(CallBackFunc callback, void *contex)
{
int n = 3;
cout << "The Option of 'callback()' is:" << callback(n, contex) << endl;
}
int main()
{
for (int i = 0; i < 10; i++)
{
if (i % 2) {
registNumCallBack(toZeroDown, &i);
}
else
{
registNumCallBack(toZeroUp, &i);
}
}
}
输出:
toZeroUp:0
The Option of 'callback()' is:toZeroUp
toZeroDown:-1
The Option of 'callback()' is:toZeroDown
toZeroUp:2
The Option of 'callback()' is:toZeroUp
toZeroDown:-3
The Option of 'callback()' is:toZeroDown
toZeroUp:4
The Option of 'callback()' is:toZeroUp
toZeroDown:-5
The Option of 'callback()' is:toZeroDown
toZeroUp:6
The Option of 'callback()' is:toZeroUp
toZeroDown:-7
The Option of 'callback()' is:toZeroDown
toZeroUp:8
The Option of 'callback()' is:toZeroUp
toZeroDown:-9
The Option of 'callback()' is:toZeroDown
该博客展示了C++中回调函数的使用,通过`registNumCallBack`函数注册`toZeroUp`和`toZeroDown`两个回调函数,根据传入参数的奇偶性决定调用哪个回调。回调函数在循环中被触发,输出了对应的整数及转换结果。
1481

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



