9-C++回调函数
·
在C++中,回调函数是一种重要的编程技术,它允许将一个函数作为参数传递给另一个函数,在特定事件发生时被调用。
1. 函数指针
返回类型 (* 函数指针名) (参数列表);
// C语言风格
#include <stdio.h>
#include <stdlib.h>
// 定义了一个指针变量,该指针变量可以指向 返回值类型为 int 型,且有两个整型参数的函数
// p 的类型为 int(*)(int,int)
typedef int (*Callback)(int, int);
void showResult(int a, int b, Callback callback) {
int sum_result = callback(a, b);
printf("%d\n", sum_result);
}
// 具体的回调函数实现
int myCallback(int value1, int value2) { return value1 + value2; }
// 具体的回调函数实现
int myCallback1(int value1, int value2) { return value1 - value2; }
int main() {
int num1 = 3; int num2 = 4;
showResult(num1, num2, myCallback);
showResult(num1, num2, myCallback1);
return 0;
}
2. std::function
std::function<返回类型(参数列表)> 对象名 ;
#include <iostream>
#include <functional>
class Button {
private:
std::function<void()> onClickCallback_;
public:
void setOnClick(std::function<void()> callback) {
onClickCallback_ = callback;
}
void click() {
std::cout << "Button clicked!" << std::endl;
if (onClickCallback_) {
onClickCallback_();
}
}
};
class Dialog {
private:
std::string name_;
public:
// 使用初始化列表的构造函数
Dialog(const std::string& name) : name_(name) {}
void showMessage() {
std::cout << "Dialog '" << name_ << "' received click event" << std::endl;
}
// 成员函数包装器
std::function<void()> getCallback() {
return [this]() { this->showMessage(); };
}
};
int main() {
Button button;
Dialog dialog("MyDialog");
// 绑定成员函数作为回调
button.setOnClick(dialog.getCallback());
button.click();
return 0;
}
5. 异步回调示例
#include <iostream>
#include <functional>
#include <thread>
#include <chrono>
class AsyncWorker {
private:
std::function<void(int)> progressCallback_;
std::function<void(const std::string&)> completionCallback_;
public:
void setCallbacks(std::function<void(int)> progress,
std::function<void(const std::string&)> completion) {
progressCallback_ = progress;
completionCallback_ = completion;
}
void startWork() {
std::thread([this]() {
for (int i = 0; i <= 100; i += 10) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
if (progressCallback_) {
progressCallback_(i);
}
}
if (completionCallback_) {
completionCallback_("Work completed successfully!");
}
}).detach();
}
};
int main() {
AsyncWorker worker;
worker.setCallbacks(
// 进度回调
[](int progress) {
std::cout << "Progress: " << progress << "%" << std::endl;
},
// 完成回调
[](const std::string& result) {
std::cout << "Result: " << result << std::endl;
}
);
worker.startWork();
// 等待异步操作完成
std::this_thread::sleep_for(std::chrono::seconds(2));
return 0;
}
回调函数是C++中实现事件驱动编程、插件架构和异步操作的重要工具,合理使用可以大大提高代码的灵活性和可维护性。
更多推荐

所有评论(0)