您的位置:首页 > 其它

笔记:解决文件互相包含问题的小方法

2007-07-16 09:55 435 查看
两个头文件互相包含,具体如下:
//------a.h ------
#ifndef _A_
#define _A_

#include "B.h"
typedef struct _Node
{
 B* pB;
 _Node* pNext;
}Node, *pNode;

class A
{
public:
 A();
 ~A();
private:
 B m_B;  //此处有问题
 Node *m_pHead;
};

#endif

//------b.h ------
#ifndef _B_
#define _B_

#include "A.h"
class B
{
public:
 B(A* pA);
 ~B();

private:
 A m_A;  //此处有问题
};
#endif

//------main.cpp ------
#include "A.h"
#include "B.h"
int main()
{
 A A();
 B B(&A);
 return 0;
}

编译时有错误,具体错误记不清了,就是一些文件包含重定义或者什么变量没有定义的错误,现在经过修改后编译通过:

//------a.h ------
#ifndef _A_
#define _A_

//#include "B.h" //修改处1
class B;   //修改处2

typedef struct _Node
{
 B* pB;
 _Node* pNext;
}Node, *pNode;

class A
{
public:
 A();
 ~A();
private:
 B* m_B;   //修改处3,记得一定要用指针,至于为什么这样现在还没想清楚
 Node *m_pHead;
};

#endif

//------b.h ------
#ifndef _B_
#define _B_

//#include "A.h" //修改处4
class A;   //修改处5
class B
{
public:
 B();
 ~B();

private:
 A* m_pA;  //修改处6,关键还是要用指针
};
#endif

//------main.cpp ------
#include "A.h"
#include "B.h"
#include <afx.h>
int main()
{
 A A();
 B B(&A);
 return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  class struct