函数指针使用

在这里例子是一个单链表节点的查找的例子:

node.h文件

/*
** Sample declaration for a linked list node.  Change this declaration
** as appropriate for your list values and recompile the linked list
** search function with it.  Note that the value can be anything you
** want -- not just a built-in type -- because your comparison function
** does the work of comparing it to the desired value.
*/


typedef 
struct  NODE  {
 
struct NODE *link;
 
int value;
}
 Node;

 

search.c文件 

 

/*
** Function to search a linked list for a specific value.  Arguments
** are a pointer to the first node in the list, a pointer to the
** value we're looking for, and a pointer to a function that compares
** values of the type stored on the list.
*/

#include 
< stdio.h >
#include 
" node.h "

Node 
*
search_list( Node 
* node,  void   const   * value,
    
int  ( * compare)(  void   const   * void   const   *  ) )
{
 
while( node != NULL )

{
  
if( compare( &node->value, value ) == 0 )
   
break;
  node 
= node->link;
 }

 
return node;
}



启示:虽然这里的Compare函数并没有写完整,可是具体Compare函数是做什么的,可以自己进行实现。

重要的是思想,其实这里的这个函数指针的使用,给我很大启示。想起来C# 里面的委托,因为C#里面没有指针,那个委托和这个函数指针很类似。通过委托实现的多态可以根据节点类型的不同来比较不同的节点,但是提供给用户的接口却可以是不变的。细节可以隐藏。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值