c++ - 无尽的包含循环

标签 c++ include-guards

<分区>

Possible Duplicate:
C header file loops

原始问题:

我总是无法理解为什么以下会出错:

something.h

#ifndef SOMETHING_H
#define SOMETHING_H

#include "somethingelse.h"

#endif

somethingelse.h

#ifndef SOMETHINGELSE_H
#define SOMETHINGELSE_H

#include "something.h"

#endif

为什么会报错?

1) SOMETHING_H 未定义

2) 定义了 SOMETHING_H,包含了 somethingelse.h

3) SOMETHINGELSE_H 未定义,已定义,并包含 something.h

4)定义了SOMETHING_H,跳转到#endif,这应该就结束了吧?


编辑:

事实证明它根本没有给出任何错误。然而,以下是:

something.h

#pragma once

#include "somethingelse.h"

class something {
    int y;
    somethingelse b;
};

somethingelse.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++ - 无尽的包含循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7946934/

相关文章:

c++ - printf 中的 %n 是什么以及如何使用它?

c++ - 为什么 C++ 标准保留换页字符?

C++ 我需要为嵌套类定义 header 保护吗?

c++ - 命名包括 guard

objective-c - 包含和导入之间的区别

c++ - 开源 Visual Studio 项目分发噩梦

c++ - 在循环中创建多个文本文件

c++ - VS2013 字 rune 字不符合 MSDN 规范

php - 防止直接访问 php 包含文件

c++ - 在包含防护中使用 #error 指令