2012-01-13 96 views
0

我有一個檢查點列表,然後運行一個函數。我最初在這個函數中創建了這個列表,但現在我必須在外部構建它。問題是我不能在執行該函數的類中包含checkpoint.h,因爲checkpoint.h返回該類的類型的結構。最初的名單在全球範圍內被宣佈爲class.c。如何將外部創建的列表轉移到課堂中,以便我可以使用它?將列表傳遞給類

所以我有這個頭,turing_machine.h

#ifndef __TURING_MACHINE__ 
#define __TURING_MACHINE__ 

#include "tape.h" 
#include "alphabet.h" 
#include "symbol_table.h" 

... 

#endif 

checkpoint.h頭定義checkpoint_list類:

#ifndef __CHECKPOINT_H__ 
#define __CHECKPOINT_H__ 

#include "turing_machine.h" 

... 

#endif 

所以我要發送到的功能從turing_machine.h結構checkpoint列表但我無法修改任何東西,因爲這就是班級必須留下的方式。

我也有turing_machine.c

#include "turing_machine.h" 
#include "checkpoint.h" 
#include "symbol_table.h" 
#include <stdlib.h> 
#include <string.h> 
#include <stdio.h> 

checkpoint_list *c; 

因此,在我創建了turing_machine該列表中,c,但現在我必須在外面創建它,我必須初始化列表c,但我不知道開始怎麼樣。我希望這更清楚。

我使用了術語類錯誤;我只有.c.h文件。

+4

目前沒有意義。當你說「checkpoint.h返回結構」時,你是什麼意思?你應該發佈一些代表性的代碼,而不是試圖描述你的代碼。 – 2012-01-13 22:45:17

+3

另外,如果他們能夠充分回答您的問題,您應該接受以前問題的一些答案。 – 2012-01-13 22:48:50

+0

在C中實現類一直很辛苦......幸運的是,那裏有一個叫做C++的新東西...你有嘗試嗎?看起來很有前途! – 2012-01-13 23:00:37

回答

0

在行之間閱讀,我覺得你的麻煩在於你有'相互參照'的結構。

來解決這一問題的方法是用一個不完整的類型定義:

typedef struct checkpoint_list checkpoint_list; 

然後,您可以使用內部turing_machine.h

#ifndef TURING_MACHINE_H_INCLUDED 
#define TURING_MACHINE_H_INCLUDED 

#include "tape.h" 
#include "alphabet.h" 
#include "symbol_table.h" 

typedef struct checkpoint_list checkpoint_list; 

typedef struct turing_machine 
{ 
    ... 
} turing_machine; 

extern checkpoint_list *tm_function(turing_machine *); 
extern turing_machine *tm_create(const char *); 

#endif 

而且,裏面checkpoint.h,你可以寫:

#ifndef CHECKPOINT_H_INCLUDED 
#define CHECKPOINT_H_INCLUDED 

#include "turing_machine.h" 

/* No typedef here in checkpoint.h */ 
struct checkpoint_list 
{ 
    ... 
}; 

extern checkpoint_list *cp_function(const char *); 
extern turing_machine *cp_machine(checkpoint_list *); 

#endif 

該技術被識別和定義由C標準(C90,更不用說C99或C11)。

請注意,我也重命名包括守衛;以雙下劃線開頭的名稱是爲'實現'(即C編譯器及其庫)保留的,您不應該在自己的代碼中創建和使用這些名稱。