C ADT 的实现
C也可实现ADT。主要是利用static关键字。static可将被修饰者的作用域限定到文件中,此文件以外则不可对它进行访问。笔者这里实现了一个简单的链表,可以参考下:
NameList.c
#include<stdlib.h>
#include<stdio.h>
static const int MAX_PEOPLE_NUM = 100;
static char* data[MAX_PEOPLE_NUM];
static int length = 0;
void insertName(char *name)
{
if (length > MAX_PEOPLE_NUM)
{
return;
}
data[length++] = name;
}
char* getName(int index)
{
if (index < 0 || index > length - 1)
{
return NULL;
}
return data[index];
}
void printList()
{
printf("%s", "{");
for (int i = 0; i < length; i++)
{
printf("%s", data[i]);
if(i != length - 1){
printf("%s", ", ");
}
}
printf("%s", "}");
}
void clear()
{
for (int i = 0; i < length; i++)
{
data[i] = NULL;
}
length = 0;
}
Main.c
#include <stdio.h>
#include <stdlib.h>
int main()
{
insertName("Rafe");
insertName("Sky");
printList(); // {Rafe, Sky}
return EXIT_SUCCESS;
}
static 将列表数据封装起来,对外只暴漏一个getName 和 insertName方法,实现了抽象数据类型(ADT)样的功能。