我正在處理C中的宏,試圖模擬objet行爲,但使用C和我有一個定義從宏中的另一個結構中的結構定義的變量的問題。這是我的代碼...它的工作原理:宏中結構的問題定義
#include <stdio.h>
#include <stdlib.h>
#define STACK_MAX_CAPACITY 10
#define DECLARE_STACK(Type) \
typedef struct MetaPile_##Type; \
\
typedef struct Pile_##Type_t{ \
Type q[STACK_MAX_CAPACITY]; \
int pos; \
} Pile_##Type; \
\
typedef struct MetaPile_##Type_t{ \
void (* push) (Pile_##Type* p, Type val); \
void (*init) (Pile_##Type* p); \
} MetaPile_##Type; \
\
void init_##Type(Pile_##Type* p){ \
p->pos = 0; \
int i; \
for(i=0; i<STACK_MAX_CAPACITY; i++){ \
p->q[i]=0; \
} \
} \
\
void push_##Type(Pile_##Type* p, Type val) { \
if(p->pos < STACK_MAX_CAPACITY){ \
p->q[p->pos]=val; \
p->pos++; \
} \
} \
MetaPile_##Type TheMetaPile_##Type; \
void initTheMetaPile_##Type(){ \
TheMetaPile_##Type.init = &init_##Type; \
TheMetaPile_##Type.push = &push_##Type; \
} \
\
DECLARE_STACK(int)
int main(){
int i;
initTheMetaPile_int();
Pile_int pi;
TheMetaPile_int.init(&pi);
push_int(&pi, 2);
push_int(&pi, 3);
push_int(&pi, 4);
push_int(&pi, 5);
push_int(&pi, 6);
for(i=0; i<STACK_MAX_CAPACITY; i++){
printf("%d",pi.q[i]);
}
return 0;
}
第一結構定義DINAMIC類型感謝的數組,表示一個客體的attributs方宏(樁_ ##型),以及其他結構(MetaPile_ ## Type),通過函數指針來管理objet的「方法」。 init函數作爲構造函數並初始化我的「objet」pi。
現在我想要在Pile _ ##類型中引用一個類型爲MetaPile _ ## Type(稱爲示例myClass)的變量,以便能夠使pi-> myClass-> push並調用功能push_int。但是,當我做:
typedef struct Pile_##Type_t{ \
Type q[STACK_MAX_CAPACITY]; \
int pos; \
MetaPile_##Type myClass; \
} Pile_##Type; \
我有一個misunderstandable錯誤...
D:\main.c|40|warning: useless keyword or type name in empty declaration|
D:\main.c|40|error: syntax error before "MetaPile_int"|
D:\main.c|40|warning: no semicolon at end of struct or union|
D:\main.c|40|warning: type defaults to `int' in declaration of `Pile_int'|
D:\main.c|40|warning: data definition has no type or storage class|
D:\main.c|40|error: syntax error before '*' token|
D:\main.c|40|error: syntax error before '*' token|
D:\main.c|40|error: syntax error before '*' token|
D:\main.c||In function `init_int':|
D:\main.c|40|error: `p' undeclared (first use in this function)|
D:\main.c|40|error: (Each undeclared identifier is reported only once|
D:\main.c|40|error: for each function it appears in.)|
D:\main.c|40|error: syntax error before '*' token|
D:\main.c||In function `push_int':|
D:\main.c|40|error: `p' undeclared (first use in this function)|
D:\main.c|40|error: `val' undeclared (first use in this function)|
D:\main.c||In function `main':|
D:\main.c|47|error: syntax error before "pi"|
D:\main.c|49|error: `pi' undeclared (first use in this function)|
||=== Build finished: 12 errors, 4 warnings ===|
我不知道做什麼用myClass相關聯的確定指標worong,我使用*也不過錯誤persits 。謝謝,如果有人可以幫助。
哇,是創建模板的C方式嗎?至少可怕...:S – 2011-03-22 22:16:19