gpt4 book ai didi

C++ - 嵌套包含 - 避免 'include nested too deeply error'

转载 作者:IT老高 更新时间:2023-10-28 23:12:03 32 4
gpt4 key购买 nike

如果我想在我的 C++ 代码中拥有以下连接,那么声明头文件的最佳方式是什么,以免出现 'include nested too deep 错误'

在我的边缘类中,我有一些需要返回 Node 对象的函数。 Edge 类也是如此,我有需要返回 Node 对象的函数。但是编译器不允许我有这个嵌套循环的东西。

Node.h

#ifndef _NODE_h__
#define __NODE_h__

#include "Edge.h"
public:
Node();
~Node();
void setName(string);
string getName();
void addEdge(Edge*);
vector<Edge* > getEdges() { return _edges; };
};
#endif

Edge.h

#ifndef _EDGE_h__
#define __EDGE_h__

#include "Node.h"
class Edge
{
public:

Edge();
Edge(bool);
~Edge();
bool hasBeenSeen() { return _seen; };
void reset() { _seen = false; }; // resets seen param to false
Node* getSource() { return _source; };
Node* getTarget() { return _target; };
void setSource(Node* source) { _source = source; };
void setTarget(Node* target) { _target = target; };
};
#endif

最佳答案

正如其他人所建议的那样,使用标题保护。但也尝试向前声明有问题的类。您可能还必须在至少一个类中使用指针(而不是值),但如果没有看到代码,我们无法判断。

所以 edge.h 应该是这样的:

#ifndef EDGE_H
#define EDGE_H

class Node; // forward declaration

Node functionB();

#endif

请注意,您必须在一个单独的 C++ 文件中定义您的函数,然后#includes "node.h"。

如果这一切看起来很复杂,那么您应该尝试简化您的设计。节点和边可能没有必要相互了解——单向依赖就足够了。

最后,包含双下划线的名称在 C++ 中是保留的——你不能在自己的代码中创建这样的名称。

关于C++ - 嵌套包含 - 避免 'include nested too deeply error',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6021720/

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