zoukankan      html  css  js  c++  java
  • C++ 使用回调函数的方式 和 作用。 持续更新

    先看两个demo:

    一.在类test1中调用函数print() ,把print()的函数指针传递给test1的函数指针参数

    test1.h:

    [cpp] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. #include <stdio.h>  
    2. #include <iostream>  
    3. using namespace std;  
    4.   
    5. typedef void (*FUNP)();  
    6. class test1  
    7. {  
    8. public:  
    9.     void fun1(FUNP p)  
    10.     {  
    11.         (*p)();  
    12.     }  
    13. };  


    main.cpp

    [cpp] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. #include <stdio.h>  
    2. #include "test1.h"  
    3.   
    4. void print();  
    5.   
    6. int main()  
    7. {  
    8.     test1 tet1;  
    9.     tet1.fun1(print);  
    10.     getchar();  
    11.     return 0;  
    12. }  
    13.   
    14. // void (*p)()  
    15. void print()  
    16. {  
    17.     printf("hello world ");  
    18. }  

    // 打印 “hello world”

    二.类Test1 中调用Test2的方法函数。  在类test2中包含test1对象,将test2中的函数指针传给test1

    test2.h:

    #include "test1.h"

    [cpp] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. #include <iostream>  
    2. using namespace std;  
    3.   
    4. class Test2  
    5. {  
    6. public:  
    7.     Test2()  
    8.     {  
    9.         tet1.fun1(fun2);  
    10.     }  
    11.     static void fun2()  
    12.     {  
    13.         cout<<"Test2"<<endl;  
    14.     }  
    15. public:  
    16.     test1 tet1;  
    17. };  

    test1.h:

    [cpp] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. #include <stdio.h>  
    2. #include <iostream>  
    3. using namespace std;  
    4.   
    5. typedef void (*FUNP)();  
    6. class test1  
    7. {  
    8. public:  
    9.     void fun1(FUNP p)  
    10.     {  
    11.         (*p)();  
    12.     }  
    13. };  

    main:

    [cpp] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. #include <stdio.h>  
    2. #include "test2.h"  
    3. int main()  
    4. {  
    5.     Test2 tet2;   
    6.     getchar();  
    7.     return 0;  
    8. }  


    // 结果:打印“Test2”

    附上两个deome,搞清楚的话 回调函数基本可以套着用了

    http://download.csdn.net/my

    http://blog.csdn.net/qq_17242957/article/details/53002652

  • 相关阅读:
    php 显示文件 与Windows文件名排序一致
    pip3 install uwsgi 报错
    centos7 安装mysql 5.7
    Win7 开始菜单搜索添加快捷方式
    centos7.7 clamav 查杀病毒
    CentOS7.x 默认php版本与php7.4共存
    centos6.5 yum安装redis
    centos6 yum安装mysql 5.6 (完整版)
    解决phpmyadmin出现: Maximum execution time of 300
    Castle Windsor 使MVC Controller能够使用依赖注入
  • 原文地址:https://www.cnblogs.com/findumars/p/6034682.html
Copyright © 2011-2022 走看看