0

可能重复:
C 头文件循环

原始问题:

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

某事.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) SOMETHING_H 被定义,somethingelse.h 被包括在内

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

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


编辑:

事实证明它根本没有给出任何错误。但是,以下内容会:

某事.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'。

问题通过正向定义解决:

某事.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”,并创建该类的实例。

4

2 回答 2

1

您的描述完全正确,除了根本没有错误。在不同的地方添加pragma message("Some text")(假设是 Visual Studio)来跟踪流程。

正如其他海报已经指出的那样,您的头文件很可能包含相互需要彼此定义的类,这就是问题的原因。此类问题通常通过以下方式解决

  • 尽可能使用前向引用
  • 尽可能将#includes 移至 CPP 文件
于 2011-10-30T18:50:59.503 回答
0

这正是发生的事情。

这称为“包含保护”,用于避免无限递归包含。

于 2011-10-30T18:42:16.147 回答