当前位置: 代码迷 >> C语言 >> 我不明白函数指针
  详细解决方案

我不明白函数指针

热度:118   发布时间:2007-02-26 15:25:15.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编辑过]


----------------解决方案--------------------------------------------------------
cdecl是什么
----------------解决方案--------------------------------------------------------
  相关解决方案