编译出错,未找到B的定义,在使用一个类时,必须找到类的定义,或者使用如下三种方法
1. 使用指针 B*b;
2. 使用引用B& b;
3. 类分成头文件,互相包含
-
class A
-
{
-
B b;
-
}
-
-
class B
-
{
-
}
-
//a.h
-
#ifndef A_H
-
#define A_H
-
#include "B.h"
-
class A
-
{
-
public:
-
A(){}
-
A(B* pB):m_pB(pB) {}
-
void useB();
-
private:
-
B* m_pB;
-
};
-
#endif
-
-
//a.cc
-
-
#include "A.h"
-
void A::useB()
-
{
-
}
-
-
//b.h
-
#ifndef B_H
-
#define B_H
-
class A;
-
class B
-
{
-
public:
-
B(A* pA):m_pA(pA) {}
-
void useA();
-
-
private:
-
A* m_pA;
-
};
-
#endif
-
-
//b.cc
-
#include "A.h"
-
#include "B.h"
-
void B::useA()
-
{
-
//do something for m_pA
-
}
-
-
//main.cc
-
#include "a.h"
-
#include "b.h"
-
-
int main()
-
{
-
A *a = new A;
-
a->useB();
-
-
B *b = new B(a);
-
b->useA();
-
delete b;
-
delete a;
-
return 0;
-
}
阅读(937) | 评论(0) | 转发(0) |