iOS指標回呼函數

來源:互聯網
上載者:User

標籤:

////  main.m//  LessonReturnFunPointer////  Created by laouhn on 15/7/29.//  Copyright (c) 2015年 池海濤. All rights reserved.//#import <Foundation/Foundation.h>#import "Function.h"int main(int argc, const char * argv[]) {     //定義兩個函數,求最大值,最小值,求和//    int value = max(3, 5);//    printf("value = %d \n", value);//        //char s[20] = "d";    //scanf("%s",&s[20]);    //shuruzhilin(3,5,(p)s);    while (1) {        printf("請輸入想要執行的操作:max 求最大值,min 最小值,sum 最大值");        char str[20] = {0};        scanf("%s", str);        int value = getValueForString(3, 5, str);        printf("value = %d\n",value);    }       return 0;}

Function.h

////  Function.h//  LessonReturnFunPointer////  Created by laouhn on 15/7/29.//  Copyright (c) 2015年 池海濤. All rights reserved.//#import <Foundation/Foundation.h>//最大值typedef int (*FUNC)(int, int);int max(int a, int b);int min(int a, int b);int sum(int a, int b);void shuruzhilin(int,int,FUNC p);typedef int (*PFUN)(int,int);struct nameFunctionPair {    char name[20];    PFUN function;    };typedef struct nameFunctionPair NameFunctionPair;//分析:根據需求,首先用於匹配的表(印射表) ---結構體數組,那麼接下來,這個表應該建立在哪?---Funtion.m檔案中int getValueForString(int a,int b, char str[]);PFUN getFunctionByName(char *string);

 

Function.m

////  Function.m//  LessonReturnFunPointer////  Created by laouhn on 15/7/29.//  Copyright (c) 2015年 池海濤. All rights reserved.//#import "Function.h"int max(int a, int b){    return a > b ? a : b;}int min(int a, int b){    return a > b ? b : a;}int sum(int a, int b){    return a + b;}void shuruzhilin(int a,int b,FUNC p){    int c = p(a,b);    printf("%d ",c);}NameFunctionPair funpair[] = {    {"max",max},    {"min",min},    {"sum",sum}};//該函數能夠幫我們實現的目標:更據字串str 匹配到相應的函數,然後,進行運算,計算兩個參數 a ,b相應的值,進行返回int getValueForString(int a,int b, char str[]){       PFUN func = getFunctionByName(str);//此時儲存的是函數指標    return func(a,b);}PFUN getFunctionByName(char *string){            for (int i = 0; i < sizeof(funpair) / sizeof(funpair[0]); i++) {        if (strcmp(string, funpair[i].name)==0) {            return  funpair[i].function;        }    }    return max;//當印射沒有傳回值,就返回max函數    }

 

iOS指標回呼函數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.