C ++类中的循环依赖 [英] Circular dependency in C++ classes
问题描述
我对C ++比较陌生,面对着一个循环依赖的问题。有人可以帮我解决这个问题吗?
I am relatively new to C++, and facing a circular dependency problem. Can someone please help me solve this?
我有两个课程:
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);
};
上述代码提供以下错误:
The above code gives following errors:
- '顶点'未命名类型
- '顶点'未声明
- 'v'
如何解决此问题?
推荐答案
所有你需要的是在顶点
Edge >:
All you need is to forward-declare the Edge
class before it's used within the Vertex
:
class Edge;
class Vertex {
string name;
int distance;
...
};
class Edge { ... };
不能放置类型顶点
而不是 Vertex
本身的声明,因为C ++不允许递归类型。在C ++的语义中,这种类型的大小需要是无限的。
You can't put members of type Vertex
instead of the declaration of Vertex
itself, since C++ doesn't allow recursive types. Within the semantics of C++, the size of such type would need to be infinite.
当然,你可以把指针放在 code>
顶点
。
You can, of course, put pointers to Vertex
within Vertex
.
你想要什么,其实在顶点
的边和邻接表,是指针,而不是对象的副本。因此,你的代码应该如下修改(假设你使用C ++ 11,你实际上应该使用现在):
What you want, in fact, within Vertex
's edge and adjacency lists, is pointers, not copies of objects. Thus, your code should be fixed like below (assuming you use C++11, which you in fact should be using now):
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 ++类中的循环依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!