【发布时间】:2011-10-30 18:40:34
【问题描述】:
可能重复:
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”,并创建类的实例。
【问题讨论】:
-
该代码根本不应该出错...你得到了什么?
-
等等,什么,这不会给我错误 O.o 在学校我了解到包含守卫不能防止无休止的包含循环 O.o。仅在文件 A 包含 B 和 C,并且文件 B 包含 C 的情况下,它只会包含 C 一次。嗯
-
他没有显示的类型不完整。
标签: c++ include-guards