将列表传递给类
问题描述:
我有一个检查点列表,然后运行一个函数。我最初在这个函数中创建了这个列表,但现在我必须在外部构建它。问题是我不能在执行该函数的类中包含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
文件。
答
在行之间阅读,我觉得你的麻烦在于你有'相互参照'的结构。
来解决这一问题的方法是用一个不完整的类型定义:
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编译器及其库)保留的,您不应该在自己的代码中创建和使用这些名称。
目前没有意义。当你说“checkpoint.h返回结构”时,你是什么意思?你应该发布一些代表性的代码,而不是试图描述你的代码。 – 2012-01-13 22:45:17
另外,如果他们能够充分回答您的问题,您应该接受以前问题的一些答案。 – 2012-01-13 22:48:50
在C中实现类一直很辛苦......幸运的是,那里有一个叫做C++的新东西...你有尝试吗?看起来很有前途! – 2012-01-13 23:00:37