★高分弱问★文件包含有关问题!
★★★高分弱问★★★文件包含问题!!!
有两个类A,B。分别在A.H,B.H中声明,在A.CPP,B.CPP中定义。类A有一个B类型的成员变量,类B有一个A指针类型的成员变量,该如何互相包含其头文件呢?
谢谢!
------解决方案--------------------
b.h
class A;前置声明
a.h
#include "b.h "
2个cpp,a.h/b.h都要include
------解决方案--------------------
//A.h
#ifndef _A_H
#define _A_H
class A;
#endif
//B.h
#ifndef _B_H
#define _B_H
#include <iostream>
using namespace std;
class B;
#endif
//A.cpp
#include "A.h "
#include "B.cpp "
class A
{
int a;
B bobj;
public:
A():a(0),bobj(B()){}
void show()
{
cout < < "A: " < <a < <endl;
}
};
//B.cpp
#include "B.h "
#include "A.h "
class B
{
int b;
A *pobj;
public:
B():b(0),pobj(0){}
void show()
{
cout < < "B: " < <b < <endl;
}
};
//main.cpp
#include <iostream>
#include "A.cpp "
#include "B.h "
using namespace std;
int main()
{
A a;
B b;
a.show();
b.show();
system( "PAUSE ");
return 0;
}
------解决方案--------------------
指针不需要定义,所以可以用前置声明。
快结贴吧,给我30分就满足了嘻嘻
------解决方案--------------------
是用前置声明就可以了。
由于B只包含A的指针,所以只要在B.h中写上
class A;
class B
{
//..........
};
------解决方案--------------------
如果B的实现(CPP)中要调用A的函数,只要把A.h包含在B.cpp文件中。
不需要再B.h中包含A.h
有两个类A,B。分别在A.H,B.H中声明,在A.CPP,B.CPP中定义。类A有一个B类型的成员变量,类B有一个A指针类型的成员变量,该如何互相包含其头文件呢?
谢谢!
------解决方案--------------------
b.h
class A;前置声明
a.h
#include "b.h "
2个cpp,a.h/b.h都要include
------解决方案--------------------
//A.h
#ifndef _A_H
#define _A_H
class A;
#endif
//B.h
#ifndef _B_H
#define _B_H
#include <iostream>
using namespace std;
class B;
#endif
//A.cpp
#include "A.h "
#include "B.cpp "
class A
{
int a;
B bobj;
public:
A():a(0),bobj(B()){}
void show()
{
cout < < "A: " < <a < <endl;
}
};
//B.cpp
#include "B.h "
#include "A.h "
class B
{
int b;
A *pobj;
public:
B():b(0),pobj(0){}
void show()
{
cout < < "B: " < <b < <endl;
}
};
//main.cpp
#include <iostream>
#include "A.cpp "
#include "B.h "
using namespace std;
int main()
{
A a;
B b;
a.show();
b.show();
system( "PAUSE ");
return 0;
}
------解决方案--------------------
指针不需要定义,所以可以用前置声明。
快结贴吧,给我30分就满足了嘻嘻
------解决方案--------------------
是用前置声明就可以了。
由于B只包含A的指针,所以只要在B.h中写上
class A;
class B
{
//..........
};
------解决方案--------------------
如果B的实现(CPP)中要调用A的函数,只要把A.h包含在B.cpp文件中。
不需要再B.h中包含A.h