c++ - 如何声明两个具有其他类型成员的结构?

标签 c++ directed-graph

我正在尝试制作一个有向图,所以我制作了一个 Graph 类,它有一个私有(private)边结构和一个私有(private)节点结构。我希望我的边有一个节点成员,它是边指向的节点,我希望我的节点有一个列表,其中包含所有远离它们的边。

#ifndef DIRECTED_GRAPH_H 
#define DIRECTED_GRAPH_H

#include <iostream>
#include <vector>
#include <string>

class Graph {
public:
    Graph( const std::string & );
    ~Graph();

    void print();

private:
    struct GNode
    {
        std::string currency_type;
        std::vector<GEdge> edges; // line 19

        GNode( std::string name ) : currency_type( name ) {}
    };

    struct GEdge
    {
        int weight;
        GNode * node; // node that the edge is pointed towards

        GEdge( int weight, GNode* node ) : weight( weight ), node( node ) {}
    };

    GNode *source;
    std::vector<GNode> nodes; 

    void add_node( const std::string & currency );
    void add_edge( const GNode *& source, const GNode *& destination, int weight );
    std::string bellman_ford( const GNode *&source );
};

#include "directed_graph.cpp"

#endif

问题是,第一个被声明的结构,在本例中是 GNode,并不知道 GEdge 的存在,这导致编译器给我错误

directed_graph.h:19: error: ISO C++ forbids declaration of ‘vector’ with no type

我该如何解决这个问题?

最佳答案

只需使用 forward declaration :

class Graph {

    // ...

private:

    struct GEdge;
//  ^^^^^^^^^^^^^
//  Forward declaration for GEdge

    struct GNode
    {
        std::string currency_type;

        std::vector<GEdge> edges; // <== This is now OK because of the
                                  //     forward declaration above

        GNode( std::string name ) : currency_type( name ) {}
    };

    struct GEdge // <== Now comes the definition of GEdge
    {
        int weight;
        GNode * node; // node that the edge is pointed towards

        GEdge( int weight, GNode* node ) 
            : weight( weight ), node( node ) {}
    };

    // ...
};

这是一个完整的 live example以上代码编译。

关于c++ - 如何声明两个具有其他类型成员的结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16513200/

相关文章:

java - 图节点(任务)的并行执行和寻找关键任务

c++ - 一定数量的像素后 SetPixel 崩溃

c++ - 如何读取没有换行符 CRLF "\r\n"的 CSV 记录?

c++ - 不确定使用哪种数据结构

javascript - 与共同的 parent 和 child 一起绘制整齐的图表

algorithm - 查找有向图中可从所有其他节点到达的节点

c++ - 在c/c++中使用变量作为对象名称的方法

c++ - C++ 编译器何时会为方法推断出 noexcept?

java - 使用递归回溯查找有向图中的所有循环

algorithm - 枚举有向图的所有最小有向环