集合对象如“菜篮子”一样,能装各种蔬菜水果。简而言之,集合对象是多态性的数据结构(Polymorphic data structure),首先使用数组表示集合对象,如下面例子,有一只球队,包含各种成员,且各有不同的角色,比如有经理、教练、球员,下面就是一般数组表述球队的组织;
首先定义一个球队的类,具体如下:
typedef struct
{
void (*init)(void *);
void (*setManager)(void*, char*);
void (*setCoach)(void*, char*);
void (*addPlayer)(void*, char*);
void (*diapaly)(void*);
char *manager,*coach,*players[20];
int i;
}BaseballTeam;
其次实现类中的元素
static void init(void* t)
{
BaseballTeam* cthis = (BaseballTeam*)t;
cthis->i = 0;
cthis->manager = NULL;
cthis->coach = NULL;
}
static void setManager(void* t, char* manager)
{
BaseballTeam* cthis = (BaseballTeam*)t;
cthis->manager = manager;
}
static void setCoach(void* t, char* coach)
{
BaseballTeam*cthis = (BaseballTeam*)t;
cthis->coach = coach;
}
static void addPlayer(void* t, char* coach)
{
BaseballTeam* cthis = (BaseballTeam*)t;
cthis->players[cthis->i] = coach;
cthis->i++;
}
static void display(void* t)
{
BaseballTeam* cthis = (BaseballTeam*)t;
int i;
printf("this team Manager is %s\n",cthis->manager);
printf("this team Coach is %s\n",cthis->coach);
for (i = 0; i < cthis->i; i ++)
{
printf("this team player is %s\n",cthis->players[i]);
}
}
void *BaseballTeamNew(void)
{
BaseballTeam *t;
t = (BaseballTeam*)malloc(sizeof(BaseballTeam));
t->init = init;
t->setCoach = setCoach;
t->addPlayer = addPlayer;
t->setManager = setManager;
t->diapaly = display;
return (void*)t;
}
最后在主函数中实现具体球队这个对象,并初始化,增加具体对象的元素:
int main(void)
{
BaseballTeam* Redteam;
Redteam =(BaseballTeam* ) BaseballTeamNew();
Redteam->init(Redteam);
Redteam->setCoach(Redteam,"Jodan");
Redteam->setManager(Redteam,"KOBI");
Redteam->addPlayer(Redteam,"JAMES");
Redteam->addPlayer(Redteam,"Daweisi");
Redteam->addPlayer(Redteam,"Tomas");
Redteam->diapaly(Redteam);
return 0;
}
使用VC6.0运行出结果。