4、C语言的面向对象
如前所说,面向对象是一种软件设计的思想,是语言无关的。在本节中,我举一个链表(list)的例子来说明如何在 C 语言中的设计出有面向对象风格的代码。
4.1 定义接口
接口是面向对象语言中的一个比较重要的概念,接口只对外部承诺实现该接口的实体可以完成什么样的功能,但是不暴露实现的方式。这样的好处是,实现者可以在不接触接口使用者的代码的情况下,对实现进行调整。
我们来看看链表的接口定义:
- #ifndef _ILIST_H
- #define _ILIST_H
- // 定义链表中的节点结构
- typedef struct node{
- void *data;
- struct node *next;
- }Node;
- // 定义链表结构
- typedef struct list{
- struct list *_this;
- Node *head;
- int size;
- void (*insert)(void *node);// 函数指针
- void (*drop)(void *node);
- void (*clear)();
- int (*getSize)();
- void* (*get)(int index);
- void (*print)();
- }List;
- void insert(void *node);
- void drop(void *node);
- void clear();
- int getSize();
- void* get(int index);
- void print();
- #endif /* _ILIST_H */
IList 接口中,可以清晰的看到,对于一个 list 实体 ( 也就是对象 ) 来说,可以在其上进行 insert, drop, clear, getSize, get(index) 以及 print 等操作。
4.2 接口的实现
构造方法:
- Node *node = NULL;
- List *list = NULL;
- void insert(void *node);
- void drop(void *node);
- void clear();
- int getSize();
- void print();
- void* get(int index);
- List *ListConstruction(){
- list = (List*)malloc(sizeof(List));
- node = (Node*)malloc(sizeof(Node));
- list->head = node;
- list->insert = insert;// 将 insert 函数实现注册在 list 实体上
- list->drop = drop;
- list->clear = clear;
- list->size = 0;
- list->getSize = getSize;
- list->get = get;
- list->print = print;
- list->_this = list;// 用 _this 指针将 list 本身保存起来
- return (List*)list;
- }
需要注意的是此处的 _ this 指针,_this 指针可以保证外部对 list 的操作映射到对 _this 的操作上,从而使得代码得到简化。
- // 将一个 node 插入到一个 list 对象上
- void insert(void *node){
- Node *current = (Node*)malloc(sizeof(Node));
- current->data = node;
- current->next = list->_this->head->next;
- list->_this->head->next = current;
- (list->_this->size)++;
- }
- // 删除一个指定的节点 node
- void drop(void *node){
- Node *t = list->_this->head;
- Node *d = NULL;
- int i = 0;
- for(i;i < list->_this->size;i++){
- d = list->_this->head->next;
- if(d->data == ((Node*)node)->data){
- list->_this->head->next = d->next;
- free(d);
- (list->_this->size)--;
- break;
- }else{
- list->_this->head = list->_this->head->next;
- }
- }
- list->_this->head = t;
- }
其他的实现代码可以参看下载部分,这里限于篇幅就不再意义列举出来。
|