在C中,我遇到了循环依赖的问题,我查看了有关这个主题的其他问题,但是真的找不到答案。
我有第一个名为顶点的结构:
#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第二个结构是顶点包含的edgelist。
#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等,但是找不到答案。
如何解决这个循环依赖问题?
发布于 2012-04-12 11:31:54
似乎你不需要在任何文件中包含任何东西。有关类型的前向申报应足够:
#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;发布于 2012-04-12 11:52:00
使用前向声明打破了这种依赖关系。这里没有包含一个包含完整结构定义的文件,而是有两种选择:
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;发布于 2012-04-12 11:40:40
我假设一个顶点需要知道什么边连接到它,而一个边需要知道它连接到哪个顶点。
如果由我决定,我会创建单独的数据类型来关联顶点和边:
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个小时,所以我很确定有一个更好的方法来设计映射类型(可能不需要多个类型),但这是我通常采用的方法。
https://stackoverflow.com/questions/10122621
复制相似问题