C++_函数指针/回调函数/std::function/std::bind
类成员函数指针 指向类中的非静态成员函数
#include <iostream> #include <functional> #include<algorithm> #include <vector> using namespace std; //函数指针指向一个类成员函数 class A { public : A( int aa = 0) :a(aa) {} ~A() {}; void SetA( int aa = 1) { a = aa; cout << "SetA" << endl; } private : int a; }; int main() { void (A::*ptr)( int ) = &A::SetA; A a;<br> //对于指向类成员函数的函数指针,引用时必须传入一个类对象的this指针,所以必须由类实体调用 A* pa = &a; (pa->*ptr)(100); } |
回调函数:函数指针作为参数传递
typedef void(*MPrint)(int a, int b); void Prints(int a,int b,const MPrint&func) { cout << a << b << endl; func(a, b); } void PrintSum(int a,int b) { cout << (a + b) << endl; } int main() { int a = 3; int b = 9; Prints(a,b, PrintSum); }
如何回调一个类成员函数?
函数指针无法指向类成员函数
使用std::bind 与std::function 结合的方式
class A { public: A(int aa = 0) :a(aa) {} ~A() {}; void SetA(int aa = 1) { a = aa; cout << "SetA" << endl; } void PrintSub(int c) { cout << (a - c) << endl; } private: int a; }; void Test(int c, std::function<void(int)>func) { cout << c << endl; func(c); } int main() { A a(9); std::function<void(int)>f1 = std::bind(&A::PrintSub, &a, std::placeholders::_1); Test(5,f1); }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!