c++中两个类相互引用

来源:互联网 发布:地产销售数据报告范文 编辑:程序博客网 时间:2024/06/05 23:03

一、问题描述

现在有两个类A和B需要定义,定义A的时候需要用到B,定义B的时候需要用到A。

二、分析

A和B的定义和调用都放在一个文件中肯定是不可以的,这样就会造成两个循环调用的死循环。

根本原因是:定义A的时候,A的里面有B,所以就需要去查看B的占空间大小,但是查看的时候又发现需要知道A的占空间大小,造成死循环。

解决方法:

(1)写两个头文件A.h和B.h分别用于声明类A和B;

(2)写两个.cpp文件分别用于定义类A和B;

(3)在A的头文件中导入B的头文件;

(4)在B的头文件中不导入A的头文件,但是用extern 的方式声明类A,并且,在B中使用A的时候要用指针的形式。

原理:在B中用指针调用A,那么在A需要知道B占空间大小的时候,就会去找到B的定义文件,虽然B的定义文件中并没有导入A的头文件,不知道A的占空间大小,但是由于在B中调用A的时候用的指针形式,B只知道指针占4个字节就可以,不需要知道A真正占空间大小,也就是说,A也是知道B的占空间大小的。

三、C++示例

A的头文件A.h:

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. #ifndef _A  
  2. #define _A  
  3. <strong>#include "B.h"//A的头文件导入了B的头文件</strong>  
  4. //extern class B;  
  5.   
  6. class A  
  7. {  
  8. private:  
  9.     B objectb;//A的头文件导入了B的头文件,在调用B的时候就可以不用指针  
  10.   
  11. public:  
  12.     A();  
  13.     int geta();  
  14.     void handle();  
  15. };  
  16.   
  17. #endif _A  


B的头文件B.h:

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. #ifndef _B  
  2. #define _B  
  3.   
  4. <strong>//#include "A.h"//B的头文件没有导入A的头文件,需要有三个地方需要注意!  
  5. extern class A;//注意1:需要用extern声明A</strong>  
  6.   
  7. class B  
  8. {  
  9. private:  
  10.     int b;  
  11.     A* objecta;//注意2:调用A的时候需要用指针  
  12. public:  
  13.     B();  
  14.     int getb();  
  15.     void handle();  
  16. };  
  17.   
  18. #endif _B  


A的定义文件A.cpp:

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. #include <iostream>  
  2. <strong>#include "A.h"</strong>  
  3.   
  4. using namespace std;  
  5.   
  6. A::A()  
  7. {  
  8.     this->a=100;  
  9. }  
  10.   
  11. int A::geta()  
  12. {  
  13.     return a;  
  14. }  
  15.   
  16. void A::handle()  
  17. {  
  18.     cout<<"in A , objectb.b="<<objectb.getb()<<endl;  
  19. }  


B的定义文件B.cpp:

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. #include <iostream>  
  2. <strong>#include "B.h"  
  3. #include "A.h"//注意3:在B.cpp里面导入A的头文件</strong>  
  4.   
  5. using namespace std;  
  6.   
  7. B::B()  
  8. {  
  9.     this->b=200;  
  10. }  
  11.   
  12. int B::getb()  
  13. {  
  14.     return b;  
  15. }  
  16.   
  17. void B::handle()  
  18. {  
  19.     objecta=new A();  
  20.     cout<<"in B , objecta->a="<<objecta->geta()<<endl;  
  21. }  


main.cpp:

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. #include <iostream>  
  2. #include <cstdlib>  
  3. <strong>#include "A.h"  
  4. //#include "B.h" //因为A.h里面已经包含B.h,所以在此不需要导入B.h了。</strong>  
  5.   
  6. using namespace std;  
  7.   
  8. void main()  
  9. {  
  10.     A a;  
  11.     a.handle();  
  12.     B b;  
  13.     b.handle();  
  14.   
  15.     system("pause");  
  16. }  
0 0