在做项目过程中遇到头文件相互包含的问题,大致情况如下:
Tree.h
#ifndef TREE_H
#def TREE_H
#include "Dialog.h"
class Tree
{
Tree();
~Tree();
...
void callDialog();
};
#endif
Tree.cpp
#include "Tree.h"
...
void Tree::callDialog()
{
Dialog *dlg = new Dialog();
....
}
....
Dialog.h
#ifndef DIALOG_H
#def DIALOG_H
#include "Tree.h"
class Dialog
{
Dialog(Tree *tree);
...
};
#endif
Dialog.cpp
#include "Dialog.h"
Dialog::Dialog(Tree *tree)
{
...
tree->leaf();
...
}
在编译的过程中提示Dialog.h中Tree未声明,分析发现头文件相互包含,在Dialog.h中包含了Tree.h,而Tree.h中包含了Dialog.h,因为头文件进行了#ifndef ... #def ... #endif的设置,推测到Tree.h中的#include"Dialog.h"时便不再包含。要解决问题可以在Dialog.h中加上前置声明class Tree,当然还不能将#include "Tree.h"去掉,因为在Dialog.cpp中有对class Tree的成员函数进行调用。