简体   繁体   English

具有struct向量的类,其中包含相同的类

[英]Class with vector of struct, which contains the same class

I have a class Node, and a struct Edge. 我有一个Node类和一个Edge结构。 But when the struct is written before the class, the struct complains for no knowing what is distance. 但是,当该结构在上课之前编写时,该结构会抱怨不知道距离是多少。 It is the same for the the way around, when the struct is define after, the classe complain for not knowing what is a Edge (the type of the vector). 遍历的方式是一样的,当在构造之后定义时,类会抱怨不知道什么是Edge(向量的类型)。

//This is my header file

typedef struct Edge Edge;
struct Edge{

   Node node;
   int distance;

};

class Node
{

  private:

  std::vector<Edge> vectorOfEdges;

};

How do I get around this error? 如何解决此错误? Thank you. 谢谢。

There is no way around this if you literally want to keep the code as it is: As far as the standard is concerned, std::vector<T> might as well literally contain elements of type T , and thus you have a cyclic mutual dependence whereby Edge contains a Node and Node contains an Edge , which does not make sense. 如果您确实要按原样保留代码,则无法解决此问题:就标准而言, std::vector<T>可能也确实包含T类型的元素,因此您有一个循环的互斥量。依赖关系,其中Edge包含一个NodeNode包含一个Edge ,这没有任何意义。

(The actual wording is that a instantiating a standard library container template on an incomplete type is undefined behaviour.) (实际用语是,在不完整类型上实例化标准库容器模板是未定义的行为。)

The typical way around this is the PIMPL idiom, by which you only provide a pointer to the element: 解决此问题的典型方法是PIMPL惯用语,通过该惯用语,您仅提供指向元素的指针

struct Edge;

class Node
{
    std::unique_ptr<std::vector<Edge>> pVecImpl;
public:
    Node() : pVecImpl(::new std::vector<Edge>) { }
    // ...
};

struct Edge
{
    // as before
};

Herb Sutter's GotW #101 describes a neat solution to abstract this pattern in a clean and attractive fashion. 赫伯·萨特(Herb Sutter)的GotW#101描述了一种干净利落的解决方案,以一种干净而吸引人的方式抽象这种图案。

(Alternatively you can also make Edge::node into a pointer.) (或者,您也可以使Edge::node成为指针。)

Your definition is circular: it tries to put a Node inside an Edge , and a vector of edges inside a Node . 您的定义是循环的:它试图将Node放置在Edge ,将向量vector放置在Node You need to make one of these a pointer, for example, like this: 例如,您需要使这些指针之一成为指针:

class Node;
struct Edge{
    Node *node;
    int distance;
};
class Node {
private:
    std::vector<Edge> vectorOfEdges;
};

PS You were missing a semicolon after the struct. 附注:您在结构后缺少分号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM