可能重复:
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”,并创建该类的实例。