加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

我们在哪里可以使用C中的函数指针,什么用于函数指针

发布时间:2020-12-16 10:45:56 所属栏目:百科 来源:网络整理
导读:就在最近,我在接受采访时被问到:我们在哪里可以使用C中的函数指针? 什么函数指针返回.我说使用我们可以使用函数指针调用函数然后他问了一些例子,但我不能满足于他更多的例子.然后他问我什么函数指针返回.我告诉他这取决于函数指针的声明. 但我真的想知道C
就在最近,我在接受采访时被问到:我们在哪里可以使用C中的函数指针?
什么函数指针返回.我说使用我们可以使用函数指针调用函数然后他问了一些例子,但我不能满足于他更多的例子.然后他问我什么函数指针返回.我告诉他这取决于函数指针的声明.

但我真的想知道C中函数指针的一些用法.

解决方法

我认为C中的经典例子是 qsort.从那里引用(我知道它是 http://www.cplusplus.com,所以一个不太好的网站,但它似乎是正确的)

void qsort ( void * base,size_t num,size_t size,int ( * comparator ) ( const void *,const void * ) );

Function that compares two elements. The function shall follow this prototype:

int comparator ( const void * elem1,const void * elem2 );

The function must accept two parameters that are pointers to elements,type-casted as void*. These parameters should be cast back to some data type and be compared.

The return value of this function should represent whether elem1 is considered less than,equal to,or greater than elem2 by returning,respectively,a negative value,zero or a positive value.

另一个“经典”的例子是计算器(例如,参见this,它是C,但它在C中是相同的).

例如,您有四个数学函数

float Plus    (float a,float b) { return a+b; }
float Minus   (float a,float b) { return a-b; }
float Multiply(float a,float b) { return a*b; }
float Divide  (float a,float b) { return a/b; }

以某种方式你选择你的操作

/* Here there should be an if or a switch/case that selects the right operation */
float (*ptrFunc)(float,float) = Plus;

你可以稍后调用它(出于某种原因你不想直接在if / switch中调用它,也许是因为你想要制作对所有操作都“常见”的其他“东西”,比如记录或打印结果)

float result = ptrFunc(1.0f,2.0f);

你可以使用函数指针的另外两件事是回调(由vine’th编写)和“穷人”虚函数(你把它们放在一个结构中,当你创建结构时(你知道,就像使用“穷人”)构造函数,但这是C所以我们将它称为初始化程序),你保存那个结构将使用的函数).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读