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);
}
复制代码

 

posted on   Animer  阅读(132)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示