[英]C++ - inclusion of typedef struct from inside a class
我的問題是關於包含一個 typedef 結構(或者至少我認為是)。 這可能很愚蠢,但我無法弄清楚我的代碼有什么問題。
我有一個Node.h
頭文件,它聲明了一個類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
的地方,因為這是我可以聲明“知道” Node
類對象是什么的EdgeInfo
的唯一地方。
然后我有一個Graph.h
頭文件,包括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
循環的error: 'EdgeInfo' was not declared in this scope
。
正如您可能看到的,我是一個 C++ 新手。 我認為通過包含Node.h
我可以像使用變量和函數一樣在類中使用“typedef struct”定義。 我錯了嗎? 或者我不明白包含在 C++ 中是如何工作的?
我希望我沒有遺漏任何細節。 十分感謝你的幫助!
“所以我發現這是我的代碼中唯一可以聲明結構的地方,因為這是我可以聲明 EdgeInfo 的唯一地方,它“知道”Node 類對象是什么。 ”
您可以使用前向聲明。 另一個鏈接: 前向聲明,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
時,它會知道EdgeInfo
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.