#include<stdio.h>
#include<stdlib.h>
typedef void *(*HANDLE)(void *);
typedef struct{
void *(*getObject)(void *);
void *(*next)(void *);
}Iterator;
#define STRING_LEN 16
typedef struct{
int pos;
char string[STRING_LEN];
}String;
char * stringGetObject(String *s){
int _pos=s->pos;
return (char *)(s->string)+_pos;
}
char * stringNext(String *s){
int _pos=1+s->pos;
if(_pos==STRING_LEN)
_pos=STRING_LEN-1;
s->pos=_pos;
return (char *)(s->string)+_pos;
}
String stringTest={0,{0,0,0}};
void init(){
int i=0;
for(i=0;i<STRING_LEN-3;i++){
stringTest.string[i]='a'+i;
}
for(i=0;i<STRING_LEN;i++){
printf("%c",stringTest.string[i]);
}
printf("\n\n");
}
Iterator iterator={(HANDLE)stringGetObject,(HANDLE)stringNext};
int main(){
Iterator *p=&iterator;
char *c=NULL;
init();
for(int i=0;i<STRING_LEN;i++){
c=(char*)(p->getObject(&stringTest));
printf("%c",*c);
p->next(&stringTest);
}
return 0;
}
typedef struct {
int data[10];
int index;
} Iterator;
int next(Iterator* it) {
return it->data[it->index++];
}
// 使用
Iterator it = { .data = {1,2,3}, .index = 0 };
printf("%d\n", next(&it)); // 输出 1