我正在尝试制作一个有向图,所以我制作了一个 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/