我是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);
};
Run Code Online (Sandbox Code Playgroud)
上面的代码给出了以下错误:
我该如何解决这个问题?
您所需要的只是在将Edge类用于以下内容之前向前声明该类Vertex:
class Edge;
class Vertex {
string name;
int distance;
...
};
class Edge { ... };
Run Code Online (Sandbox Code Playgroud)
您不能放置类型的成员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);
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3010 次 |
| 最近记录: |