2014-05-17 28 views
0

我有一個C cfg_struct,其中包含有關如何評估某些數據的信息。爲了避免評估代碼中的switch,我將正確的評估函數分配給結構本身。如果在自己的定義中使用它,我是否必須預定義類型/結構?

//Some evaluation function 
int eval2(cfg_struct* cfg, int*data); 
int eval3(cfg_struct* cfg, int*data); 
int eval4(cfg_struct* cfg, int*data); 
... and so on 

然後是結構應該是這樣的:

struct cfg_struct 
{ 
    int rule; 
    ... 
    int(*eval_fn)(cfg_struct *cfg, int* data); 
}; 

和錯誤:

error: unknown type name 'cfg_struct' 

我試圖預定義,但能不能做到?

//My "predefinition": 
typedef struct cfg_struct; 
+0

'typdef struct'什麼?你需要命名你正在做別名的結構。 –

+0

ca_cfg_t應該是什麼?只需要一個'struct cfg_struct'的typedef? – cegfault

+0

另外,您在某些地方使用'cfg_struct',而不是'ca_cfg_t'。 –

回答

2

在使用它之前定義的類型:

typedef struct cfg_struct ca_cfg_t; 

struct cfg_struct 
{ 
    int rule; 
    ... 
    int(*eval_fn)(ca_cfg_t *cfg, int *data); 
}; 

或者使用struct符號的結構:

struct cfg_struct 
{ 
    int rule; 
    ... 
    int(*eval_fn)(struct cfg_struct *cfg, int *data); 
}; 

typedef struct cfg_struct ca_cfg_t; 

也似乎有什麼時候可以滴一些混亂struct。在C中(與C++不同),您必須提供明確的typedef或繼續使用struct tag。所以,你的evalX()功能要求之一:

typedef struct cfg_struct cfg_struct; 
int eval2(cfg_struct *cfg, int *data); 

或:

int eval2(ca_cfg_t *cfg, int *data); 

或:

int eval2(struct cfg_struct *cfg, int *data); 

(在C++中,你可以使用標籤名稱作爲類型名稱,而不struct前綴沒有顯式typedef,只要struct cfg_struct(或class cfg_struct)出現在某處,但這不是C的一部分)。

相關問題