2010年5月16日星期日

C语言对数据的隐藏封装

在C++中,如果我们想把数据结构隐藏起来,只为用户提供接口,可以通过实现继承接口类的方式到达目的。那C中,可以采用什么方式呢。下面有一例:
// demo.h
#ifndef DEMO_H
#define DEMO_H

typedef struct Demo* Demo;

extern Demo DemoCreate(int num);
extern void DemoDestory(Demo demo);
extern void DemoShow(Demo demo);

#endif//DEMO_H

// demo.c
#include "demo.h"
#include <stdio.h>
#include <stdlib.h>

typedef struct Demo_ {
int num_;
} Demo_;

Demo DemoCreate(int num) {
Demo_* demo = (Demo_*)malloc(sizeof(Demo_));
demo->num_ = num;
return (Demo)demo;
}

void DemoDestory(Demo demo) {
free(demo);
}

void DemoShow(Demo demo) {
printf("%d\n", ((Demo_*)demo)->num_);
}

// main.c
#include "demo.h"

int main() {
Demo demo = DemoCreate(888);
DemoShow(demo);
DemoDestory(demo);
return 0;
}

用户只需要有demo.h文件,即可使用Demo模块。Demo的内部细节被隐藏在demo.c中。

2010年5月4日星期二

这一年……

这一年,我来北京了。

顺利找到一份工作。

认识了一些朋友。

听到几首歌……

“我要走在我的路上,我要走在我的路上……”

哈哈~