C++ - 从类内部包含 typedef 结构

标签 c++ struct include

我的问题是关于包含 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 scopefor循环。

正如您可能看到的,我是一个 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.cppGraph.h 中包含 node.h 时,它会识别 边缘信息

关于C++ - 从类内部包含 typedef 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41502310/

相关文章:

include - Jade中的 "extends"和 "include"有什么区别?

c++ - 编写自定义迭代器——如果您位于数组末尾怎么办?

c++ - 如何从 C++ 控制台应用程序使用 shell32.dll

c++ - 为什么我们在对自定义对象的 vector 进行排序时在结构定义中包含比较函数?

c - 读/写/修改 C 中的结构

C# 泛型和约束

C Visual 2008 正在尝试在 ifdef 之外包含适用于 Linux 的库

c++ - 使用二维字符数组的内容填充字符串的C++ vector :大小太大时失败

c++ - 如何将比较器作为函数的参数传递?

javascript - 脚本的可见性包含在 IFRAME 中