+-

我是C的新手,面临循环依赖问题.有人可以帮我解决这个问题吗?
我有两节课:
class Vertex {
string name;
int distance;
//Vertex path;
int weight;
bool known;
list<Edge> edgeList;
list<Vertex> adjVertexList;
public:
Vertex();
Vertex(string nm);
virtual ~Vertex();
};
class Edge {
Vertex target;
int weight;
public:
Edge();
Edge(Vertex v, int w);
virtual ~Edge();
Vertex getTarget();
void setTarget(Vertex target);
int getWeight();
void setWeight(int weight);
};
上面的代码给出了以下错误:
>’Vertex’没有命名类型
>’Vertex’尚未申报
>预期’)’在’v’之前
我该如何解决这个问题?
最佳答案
您只需要在Edge类中使用它之前向前声明Edge类:
class Edge;
class Vertex {
string name;
int distance;
...
};
class Edge { ... };
您不能放置Vertex类型的成员而不是Vertex本身的声明,因为C不允许递归类型.在C的语义中,这种类型的大小需要是无限的.
当然,您可以在Vertex中指向Vertex.
事实上,在Vertex的边缘和邻接列表中,您想要的是指针,而不是对象的副本.因此,您的代码应该像下面一样修复(假设您使用C 11,实际上您现在应该使用它):
class Edge;
class Vertex {
string name;
int distance;
int weight;
bool known;
list<shared_ptr<Edge>> edgeList;
list<shared_ptr<Vertex>> adjVertexList;
public:
Vertex();
Vertex(const string & nm);
virtual ~Vertex();
};
class Edge {
Vertex target;
int weight;
public:
Edge();
Edge(const Vertex & v, int w);
virtual ~Edge();
Vertex getTarget();
void setTarget(const Vertex & target);
int getWeight();
void setWeight(int weight);
};
点击查看更多相关文章
转载注明原文:C类中的循环依赖 - 乐贴网