我的问题是关于包含 typedef 结构(或者至少我认为是)。这可能很愚蠢,但我无法弄清楚我的代码出了什么问题。
我有一个Node.h
声明类的 header Node
:
class Node {
public:
Node(/*some parameters*/); // Class constructor
typedef struct{ // This represents a weighted edge of weight "weight" from the current node to another node "node"
Node* node;
double weight;
}EdgeInfo;
vector<EdgeInfo*> OutEdges; // This vector represents the outgoing weighted edges from this node
};
所以我发现这是我的代码中唯一可以声明 struct
的地方因为这是我唯一可以声明EdgeInfo
的地方“知道”什么是Node
类对象是。
然后我有一个Graph.h
header ,包括 Node.h
文件,声明 Graph
类。
现在在Graph.cpp
文件我正在实现一个函数,该函数在 Node
的所有传出边缘上循环,或多或少像这样:
Node* current = /*passing an object of class Node*/
for(EdgeInfo* out : current->OutEdges){
/*working on the edges*/
}
问题是,当我编译时,出现错误 error: ‘EdgeInfo’ was not declared in this scope
在for
循环。
正如您可能看到的,我是一个 C++ 新手。我认为通过包含 Node.h
我可以在类中使用“typedef struct”定义,就像使用变量和函数一样。我错了吗?或者我不明白 include 如何在 C++ 中工作?
我希望我没有错过任何细节。非常感谢您的帮助!
最佳答案
“所以我发现这是我的代码中唯一可以声明结构的地方,因为这是我可以声明 EdgeInfo“知道”Node 类对象是什么的唯一地方。“
您可以使用forward declaration 。另一个链接:forward declaration, stackoverflow .
class Node; // forward declaration
struct EdgeInfo
{
Node* node; // now, `EdgeInfo` knows that a class named `Node` is defined somewhere.
double weight;
};
class Node {
public:
Node(/*some parameters*/); // Class constructor
vector<EdgeInfo*> OutEdges; // This vector represents the outgoing weighted edges from this node
};
现在,当您在 graph.cpp
或 Graph.h
中包含 node.h
时,它会识别 边缘信息
。
关于C++ - 从类内部包含 typedef 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41502310/