簡體   English   中英

C++ - 從類內部包含 typedef 結構

[英]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.cppGraph.h包含node.h時,它會知道EdgeInfo

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM