无尽的include循环
endless include loops
可能重复:
C头文件循环
原始问题:
我一直很难理解为什么下面会出现错误:
something.h
#ifndef SOMETHING_H
#define SOMETHING_H
#include "somethingelse.h"
#endif
某种东西。h
#ifndef SOMETHINGELSE_H
#define SOMETHINGELSE_H
#include "something.h"
#endif
为什么会出现错误?
1( 未定义SOMETHING_H
2( 某些东西被定义,某些东西被包含在中
3( SOMETHINGELSE_H未定义,变成已定义,并且something.H包含
4( 定义了SOMETHING_H,跳转到#endif,这应该是它的结尾吗?
编辑:
事实证明它根本没有任何错误。然而,以下情况确实存在:
something.h
#pragma once
#include "somethingelse.h"
class something {
int y;
somethingelse b;
};
某种东西。h
#pragma once
#include "something.h"
class somethingelse {
something b;
int x;
};
这是合乎逻辑的,因为当"somethingelse"需要一个类的实例时,类"something"还没有定义。
问题通过正向定义解决:
something.h
#pragma once
class somethingelse;
class something {
int y;
somethingelse* pB; //note the pointer. Correct me if I'm wrong but I think it cannot be an object because the class is only declared, not defined.
};
在.cpp中,可以包含"somethingelse.h",并生成类的实例。
您的描述完全正确,只是没有任何错误。在不同的位置添加pragma message("Some text")
(假定为Visual Studio(以跟踪流。
正如其他海报已经指出的那样,头文件很可能包含相互需要定义的类,这就是问题的原因。这类问题通常由解决
- 尽可能使用正向参考
- 尽可能将
#include
移动到CPP文件
这正是发生的事情。
这被称为"包含保护",用于避免无限递归的包含。
相关文章:
- 如何循环打印顶点结构
- 如何在C++中从两个单独的for循环中添加两个数组
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 正在尝试了解输入验证循环
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- 循环后如何继续阅读
- Ardunio UNO解决了多个重叠的定时器循环
- Eigen如何在容器循环中干净地附加矩阵
- 在某些循环内使用vector.push_back时出现分段错误
- 既然存在危险,为什么项目要使用-I include开关
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 有充分的理由在h文件中使用include保护而不是cpp文件吗
- 如何处理模板类标头中的循环 #include 调用
- 实现递归函数,避免由 C++ 中 include 的循环调用(没有 #pragma 一次)引起的无限循环输入
- 如何避免涉及全局变量的循环 #include?
- C++:由于 #include 循环,无法将对象实例传递给另一个类
- #include 循环依赖项错误
- 如何解决此循环include
- friend函数和include循环
- 无尽的include循环