您的位置:首页 > 编程语言 > C语言/C++

c语言 第三讲 函数指针和结构体结合调用

2014-07-22 16:35 453 查看
#include <stdio.h>

#include <string.h>

#include "Myfunction.h"

int maxValue(int x,int y)

{

return x > y ? x : y;

}

int minValue(int x,int y)

{

return x < y ? x : y;

}

int sumValue(int x,int y)

{

return x + y;

}

int avgValue(int x,int y)

{

return (x + y) /
2;

}

PFUNC getFunction(constchar *funcName)
//返回函数指针

{

KeyFunc kFuncs[4] = {

{"max",maxValue},

{"min",minValue},

{"sum",sumValue},

{"avg",avgValue}

};

//从数组匹配出的函数指针

PFUNC pFunc =
NULL;

for (int i =0; i <
4; i++) {

if (strcmp(kFuncs[i].funcName, funcName) ==0) {

pf = kFuncs[i];

break;

}

}

return pf;

}

int getValue(int x,int y,
constchar *funcName)
//得到pf的地址,pf指x,y具体所要操作的函数!

{

//通过函数名称字符串得到函数指针

PFUNC pf = getFunction(funcName);

//没有匹配到,返回0,如果pf不为空,直接调用pf(x, y)

int result = 0;

if (pf) {
//pf != null

result = pf(x, y);

}

return result;

}

int main(int argc,const
char * argv[])

{

char funcName[20] = {'\0'};

scanf("%s", funcName);

printf("%s = %d\n", funcName,getValue(3,5,
funcName));

return 0;

}

int maxValue(int x,int y);

int minValue(int x,int y);

int sumValue(int x,int y);

int avgValue(int x,int y);

//typedef int (*)(int, int) PFUNC;

typedef int (*PFUNC)(int,int);
//重定义为 PEUNC = int (*)(int, int)

/// 通过字符串函数名字得到函数指针

PFUNC getFunction(constchar *funcName);

int getValue(int x,int y,
const
char *funcName); //原始int (*pf)(int, int); 即等于PFUNC pf

/// 结构体保存字符串名字和函数指针

typedef struct keyFunc {

char *funcName;

PFUNC pFunc;

} KeyFunc;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐