我在 C 中存在循环依赖的问题,我查看了有关此主题的其他问题,但实际上找不到答案。
我有第一个名为vertex的结构:
#ifndef MapTest_vertex_h
#define MapTest_vertex_h
#include "edgelist.h" //includes edgelist because it's needed
typedef struct
{
char* name;
float x, y;
edgelist* edges;
} vertex;
#endif
第二个结构是顶点包含的边缘列表。
#ifndef edgelist_h
#define edgelist_h
#include "edge.h" //include edge, because its needed
typedef struct _edgelist
{
edge** edges;
int capacity, size;
} edgelist;
//...
#endif
然后是最后一个结构,即问题引发的结构,边结构包含在上面的边缘列表中。
#ifndef MapTest_edge_h
#define MapTest_edge_h
#include "vertex.h" //needs to be included because it will be unkown otherwise
typedef struct
{
float weight;
vertex* destination;
int found;
} edge;
#endif
我尽我所能,使用#ifndef
,#define
等进行声明,但无法找到答案。
如何解决此循环依赖性问题?
答案 0 :(得分:10)
好像你不需要在任何文件中包含任何内容。相关类型的前瞻性声明应该足够:
#ifndef MapTest_vertex_h
#define MapTest_vertex_h
struct edgelist;
typedef struct
{
char* name;
float x, y;
edgelist* edges; // C++ only - not C
} vertex;
#endif
等。在C编码中,你必须写:
struct edgelist;
typedef struct
{
char* name;
float x, y;
struct edgelist* edges;
} vertex;
答案 1 :(得分:2)
使用转发声明打破了这种依赖关系。不是包含具有结构的完整定义的文件,而是有两种选择:
1
typedef struct
{
char* name;
float x, y;
struct _edgelist* edges; /* add "struct" here (elaborated type specifier) */
} vertex;
2
struct __edgelist; /* better form: forward declaration */
typedef struct
{
char* name;
float x, y;
struct _edgelist* edges; /* still need to add "struct" here */
} vertex;
答案 2 :(得分:1)
我假设顶点需要知道哪些边连接到它,并且边需要知道它连接到哪个顶点。
如果由我决定,我会创建单独的数据类型来关联顶点和边缘:
struct vertex {
char *name;
float x, y;
};
// edgelist as before
struct edge {
float weight;
int found;
};
// New struct to map edges and vertices
struct vertexEdge { // you can probably come up with a better name
struct vertex *v;
struct edgelist *edges;
};
// New struct to map vertices and edges
struct edgeVertext {
{
struct edge *e;
struct vertex *vertices;
};
本周我睡了大约10-12个小时,所以我很确定有更好的方法来设计映射类型(可能以不需要多种类型的方式),但这是我采取的一般方法。