gpt4 book ai didi

c++ - C++ 类中的循环依赖

转载 作者:太空宇宙 更新时间:2023-11-04 12:41:04 24 4
gpt4 key购买 nike

我是 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);
};

以上代码报错如下:

  • “顶点”没有命名类型
  • “顶点”尚未声明
  • 应在“v”之前使用“)”

我该如何解决这个问题?

最佳答案

您需要做的就是在 Vertex 中使用前向声明 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++ - C++ 类中的循环依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54208705/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com