| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 527 人关注过本帖
标题:我不明白函数指针
只看楼主 加入收藏
zerocn
Rank: 1
等 级:新手上路
帖 子:126
专家分:0
注 册:2006-4-11
收藏
 问题点数:0 回复次数:3 
我不明白函数指针
看下去似懂非懂的,根本就不会运用
搜索更多相关主题的帖子: 指针 函数 似懂非懂 根本 
2007-02-26 15:25
田里兵蜂
Rank: 1
等 级:新手上路
威 望:2
帖 子:604
专家分:0
注 册:2007-1-29
收藏
得分:0 
不懂就学呀,多做试验
写些小程序验证下就明白了

2007-02-26 15:27
ChenMo
Rank: 16Rank: 16Rank: 16Rank: 16
等 级:版主
威 望:3
帖 子:481
专家分:10
注 册:2004-4-8
收藏
得分:0 

C语言中,变量与函数(属性与行为——面向对象思想)是分离的,
然而当在描述数据结构时,声明一种结构类型,如常规的单向链表的结点类型(单出度),
面向对象思想是将该类型的所有相关属性及作用在该类型上的函数聚合在一起。
理由是它们本应该是这样。
由于函数与结构是分离的,使得类型的结构显得相当松散,此时可以使用函数的指针将它们整合到一起。

下面是一个使用了函数指针的例程(在 Node_New() 函数中将被使用),我将使用面向对象的思想来实现这个结点类型,
需要事先声明的是,面向对象的易维护性是无可否认的好处,然而无论这种方法实现数据结构的好坏如何,
这个例程仅用来说明函数指针的使用:

#define True 1
#define False 0

#define Malloc(type) (type*) malloc(sizeof(type))
#define Free(pointer) free(pointer)

typedef int BOOL;

typedef struct Node Node;
struct Node
{
void* m_data;
Node* m_next;

BOOL (*SetData)(Node* this, void* data);
void* (*GetData)(Node* this);

BOOL (*SetNext)(Node* this, Node* next);
Node* (*GetNext)(Node* this);
};

BOOL cdecl Node_SetData(Node* this, void* data)
{
if (!this) return (False);
this->m_data = data;
return (True);
}

void* cdecl Node_GetData(Node* this)
{
if (!this) return (NULL);
return (this->m_data);
}

BOOL cdecl Node_SetNext(Node* this, Node* next)
{
if (!this) return (False);
this->m_next = next;
return (True);
}

Node* cdecl Node_GetNext(Node* this)
{
if (!this) return (NULL);
return (this->m_next);
}

Node* cdecl Node_New(void)
{
Node* node = Malloc(Node);
if (node)
{
node->m_data = NULL;
node->m_next = NULL;
node->SetData = Node_SetData;
node->GetData = Node_GetData;
node->SetNext = Node_SetNext;
node->GetNext = Node_GetNext;
}
return (node);
}

BOOL cdecl Node_Delete(Node* this)
{
void* data;
if (!this) return (False);
data = this->GetData(this);
if (data) Free(data);
Free(this);
this = NULL;
return (True);
}

可能让人疑惑的是,这样的实现明显复杂得多,
而且 Node 类型的执行速度要比使用常规方法的实现要慢,因为属性将被隐藏起来,
只能通过接口存取,这是面向对象的设计准则。
—— 但是它们显然体现了类型的封装性。

[此贴子已经被作者于2007-2-27 13:31:08编辑过]


欢迎加入 MVC 技术讨论群(新群:90093426)
2007-02-27 13:28
C语言学习者
Rank: 4
等 级:贵宾
威 望:13
帖 子:1278
专家分:0
注 册:2006-9-26
收藏
得分:0 
cdecl是什么

谁有强殖装甲第二部,可以Q我460054868
2007-02-27 13:50
快速回复:我不明白函数指针
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.016866 second(s), 9 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved