<分区>
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”,并创建该类的实例。