2020年5月23日 星期六

C/C++ - Function Pointer 應用 CallBack Function

Function Pointer 應用 CallBack Function


    有了 Function Pointer 就意味著,Callback Function 能被實現。    
Callback Function : 
A 跟 B 講 "看到 C 就打電話給我"
打電話給 A = Callback Function
    main.cpp ( A )
    int 
    main () {
        // 從 0 數到 10000000,中間請回報進度 % 數
        zeroTo(1000000, ShowPercentage);
        return 0;
    }
    zeroTo ( B ) 每數一個數字 ( 看到 C )
    void 
    zeroTo (size_t targetNumber, CallBackFuncPtr func) 
    {
        for (size_t i = 0; i < targetNumber; i++){
            func((i * 100) / targetNumber);
        }
    }
    ShowPercentage ( 打電話給 A )
    typedef void (*CallBackFuncPtr)(size_t);
    void ShowPercentage(size_t percentage)
    {
        std::cout << "\rProcessing :\t" << percentage << "%";
    }


相關文章 : 

Related Posts:

  • C 語言 - malloc、free 與 calloc malloc 跟 free     一般來說要將函式結果回傳是不能用 pointer,因為一旦函式結束 stack 的空間就會被釋出,所以 pointer 會指向的資料是危險的。這時就會先動態地宣告一個位址給 pointer,但這類的記憶體會被存放在 heap 而非 stack,所以開發者必須自行釋放。 pointer.c void showMalloc(int poi… Read More
  • C/C++ - Function Pointer 應用 CallBack FunctionFunction Pointer 應用 CallBack Function     有了 Function Pointer 就意味著,Callback Function 能被實現。     Callback Function : A 跟 B 講 "看到 C 就打電話給我" 打電話給 A = Callback Function     main.cpp ( A ) … Read More
  • C 語言 - struct array 初始化 ( Initializing array of structures ) 初始化 struct array struct student { char* name; int grade; int id; }; 1. 依照當初宣告的順序 struct student myStudents[] = { {"Henry", 3, 1}, {"Marry", 3, 2} }; 1. 依照當初宣告的名子 … Read More
  • C 語言 - CLI ( Command Line Interface ) 設計 (1)CLI 命令列介面     在設計 CLI 的程式時,最好的方法是遵從 IEEE Std 1003 ( POSIX ) 對 program 的 command-line options 之規範。所以用 getopt 去做 parse command-line 是最簡單的,有一點要注意的是 GNU 提供的 getopt 支援 " -- ",這個 PO… Read More
  • C 語言 - warning: left shift count >= width of type warning: left shift count >= width of type     一般來說,就是 shift 的 bit 大於資料型態的 bit 數。但有時使用 unsigned long 仍然會出錯,因為 unsigned long 會依照系統的不同,有時是 32 bit 有時是 64 bit,所以這時用 unsigned long long 較為安全 ( 保證 64 bit… Read More

0 意見:

張貼留言

Popular Posts