总所周知,我们想要调用一个类,一定要添加他的头文件。例如,class A 调用class B,
在class A 头文件中,这样子就可以了。如:
A.h
#ifndef A_H
#define A_H
#include "B.h"
class A
{
public:
A();
B b;
};
#endif
但是,如果我想class A 调用class B , class B 调用class A呢,如果使用A的头文件包含B的头文件,B的头文件包含A的头文件,这样是否可行?
a.h
#ifndef A_H
#define A_H
#include "b.h"
class A
{
public:
A();
B b;
};
#endif // A_H
b.h
#ifndef B_H
#define B_H
#include "a.h"
class B
{
public:
B();
A a;
};
#endif // B_H
编译出错
b.h:8: error: 'A' does not name a type
所以,这样不行的。
---------------------下面才是正确的办法----------------------------------
直接上代码:
a.h
#ifndef A_H
#define A_H
class B;
class A
{
public:
A();
B *b;
};
#endif // A_H
a.cpp
#include "a.h"
#include "b.h"
A::A()
{
}
为什么在a.cpp中include b.h,因为需要调用b的接口。
b.h
#ifndef B_H
#define B_H
#include "a.h"
class B
{
public:
B();
A a;
};
#endif // B_H
还有一种办法,在A,B类头文件中相互引用头文件,将A或者B设计为单例模式。