/* Main program ---calls--> Library function ---calls--> Callback funtion */ #include <stdio.h> #include <stdlib.h> typedef double (*op_fun)(double, double);/*函数指针的第一种定义方式,比较奇怪为什么不是 double () (double, double) * op_fun; 这种形式。*/ typedef struct _OP { double (*add)(double, double); /*函数指针第二种定义方式*/ double (*sub)(double, double); double (*mul)(double, double); //double (*div)(double, double); op_fun div; } OP; double add(double a, double b) { return a + b; } double sub(double a, double b) { return a - b; } double mul(double a, double b) { return a * b; } double div(double a, double b) { return a / b; } void OP_init(OP * op) { op->add = add; op->sub = sub; /*函数指针第一种赋值方式*/ op->mul = &mul; /*函数指针第二种赋值方式*/ op->div = ÷ } /*Library function*/ double lib_fun(double a, double b, double (*op)(double, double)) { return op(a, b); //return (*op)(a, b); } //double (*op_arr[5])(double, double); /*声明函数指针数组的第一种方式*/ op_fun op_arr[5]; /*声明函数指针数组的第二种方式*/ void op_arr_init() { op_arr[1] = add; op_arr[2] = sub; op_arr[3] = &mul; op_arr[4] = ÷ } double (* get_op(int num))(double, double) /*函数指针作为返回值,get_op参数为(int num),返回类型为double(*)(double, double)*/ { op_arr_init(); if (1 <= num && num <= 4) return op_arr[num]; return NULL; } int main(int argc, char const *argv[]) { OP * op = (OP *)malloc(sizeof(OP)); OP_init(op); double a, b; scanf("%lf %lf", &a, &b); printf("ADD = %lf, SUB = %lf, MUL = %lf, DIV = %lf ", (op->add)(a, b), (op->sub)(a, b), /*函数指针第一种调用方式*/ (*op->mul)(a, b), (*op->div)(a, b)); /*函数指针第二种调用方式*/ printf("ADD = %lf, SUB = %lf, MUL = %lf, DIV = %lf ", lib_fun(a, b, add), lib_fun(a, b, sub), lib_fun(a, b, mul), lib_fun(a, b, div)); free(op); int num; printf("Input operation(1:add, 2:sub, 3:mul, 4:div): "); scanf("%d", &num); if (num) printf("Answer is %lf ", lib_fun(a, b, get_op(num))); else printf("Wrong! "); return 0; }