• 【C++学习】函数指针


    #include //包含头文件
    using namespace std; 
    void func(int no, string str){
        cout << "亲爱的"<< no << "号:" << str << endl;
    }
    
    int main(){
        int bh = 3;
        string message = "我是一只傻傻鸟";
        func(bh, message);
        void(*pfunc)(int,string); //声明函数的函数指针
        pfunc = func;
        pfunc(bh,message); // c++的方式 用函数指针名调用函数。
        void(*pfunc1)(int,string) = func; 
        pfunc1(bh,message); 
        (*pfunc)(bh,message); //用函数指针名调用函数,C语言
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    函数指针的应用场景,主要是用于回调,用个函数指针,调用方自己实现函数的内容,但调用方式和入参由自己定义。

    #include //包含头文件
    using namespace std; 
    void func(int no, string str){
        cout << "亲爱的"<< no << "号:" << str << endl;
    }
    
    void ls(){
        cout << "我是ls的表白方式:" << "对你爱爱爱不完" << endl;
    }
    
    void zs(){
        cout << "我是zs的表白方式:" << "他一定很爱你" << endl;
    }
    
    void ls(int a){
        cout << "我是ls的表白方式:" << "对你爱爱爱不完:" << a << endl;
    }
    
    void zs(int a){
        cout << "我是zs的表白方式:" << "他一定很爱你:" << a << endl;
    }
    void show(void(*pf)()){
        cout << "表白之前的准备工作完成。\n";
        pf();
        cout << "表白之后的收尾工作已完成。\n";
    }
    
    void show(void(*pf)(int),int a){
        cout << "表白之前的准备工作完成。\n";
        pf(a);
        cout << "表白之后的收尾工作已完成。\n";
    }
    int main(){
        int bh = 3;
        string message = "我是一只傻傻鸟";
        func(bh, message);
        void(*pfunc)(int,string); //声明函数的函数指针
        pfunc = func;
        pfunc(bh,message); // c++的方式 用函数指针名调用函数。
        void(*pfunc1)(int,string) = func; 
        pfunc1(bh,message); 
        (*pfunc)(bh,message); //用函数指针名调用函数,C语言
        
        cout << "===============" << endl;
        // 不传参的方式
        show(ls); //李四要表白
        show(zs); // 张三要表白
        // 传参的方式
        cout <<"-------------------"<< endl;
        show(ls,3);
        show(ls,4);
    }
    
    • 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
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
  • 相关阅读:
    分布式Session如何存储
    WWW2024 | PromptMM:Prompt-Tuning增强的知识蒸馏助力多模态推荐系统
    威锋VL211是USB 3.1 Gen1集线器控制器,完全符合USB 3.1 Gen1规范
    品牌低价的形式有哪些
    GBase 8c导出单个数据库
    node.js的express模块实现GET和POST请求
    Db2 license
    【云原生之k8s】k8s基础详解
    使用 Containerlab + Kind 快速部署 Cilium BGP 环境
    spring中那些让你爱不释手的代码技巧(续集)
  • 原文地址:https://blog.csdn.net/weixin_40293999/article/details/132596055