gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 02:13:24 27 4
gpt4 key购买 nike

我的问题是关于包含 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*/
}

问题是,当我编译时,在 for 循环中出现错误 error: ‘EdgeInfo’ was not declared in this scope

正如您可能看到的那样,我是一个 C++ 新手。我认为通过包含 Node.h,我可以在类中使用“typedef struct”定义,就像我使用变量和函数一样。我错了吗?还是我不了解 includes 在 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 时,它会知道 EdgeInfo.

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com