一、作用
1. 提高代码阅读性
2. 分类管理函数及部分属性
3. 偏向于c++的面向对象思维
二、使用方法:
1. 声明结构体函数
2. 初始化结构体函数
3. 调用结构体函数
三、示例
#include<stdio.h> #include<stdlib.h> /*structure declare*/ struct str_func{ int a; int b; int (*add)(int a, int b); int (*sub)(int a, int b); int (*compare)(int a, int b); }; int add(int a, int b){ return a+b; } int sub(int a, int b){ return a - b; } int compare(int a, int b){ if (a>b) return a; else return b; } /*create a structure and init*/ struct str_func test = { .a = 5, .b = 7, .add = add, //function pointer point to function .sub = sub, .compare = compare, }; int main(){ if (test.compare) printf("a b max = %d\n",(test.compare(test.a,test.b))); if (test.compare) printf("a add b = %d\n",(test.add(test.a,test.b))); if (test.compare) printf("a sub b = %d\n",(test.sub(test.a,test.b))); return 0; }
编译及运行结果:
摘自:https://blog.csdn.net/sinat_29891353/article/details/83067747
原文地址:https://www.cnblogs.com/huachunwei/p/12143970.html
时间: 2024-10-10 20:56:00