C++中两个类互相包含的策略

来源:互联网 发布:户外徒步地图软件 编辑:程序博客网 时间:2024/05/22 03:26
C++中两个类互相包含的策略

一,问题描述

        A类包含B类的实例,而B类也包含A类的实例

 

二,求解策略

 

        1)错误的解法

               A文件包含B,而B文件又包含A文件,这样就形成死循环

[html] view plaincopy
  1. #include "B.h"  
  2.   
  3. class A  
  4. {  
  5.     int i;  
  6.     B b;  
  7. };  
  8.   
  9. #include "A.h"  
  10. class B  
  11. {  
  12.     int i;  
  13.     A   a;  
  14. };  


         2)正确的写法以及注意事项

                1)主函数只需要包含b.h 就可以,因为b.h中包含了a.h

              2)a.h中不需要包含b.h,但要声明class   b。在避免死循环的同时也成功引用了b

              3)包含class  b 而没有包含头文件 "b.h",这样属于一种前向声明,那么只能声明b类型的指针或引用,一定不能实例化。

            

 

       a.h:

[html] view plaincopy
  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. class b;  
  5.   
  6. class a  
  7. {  
  8. public:  
  9.     b *ib;  
  10.     void putA()  
  11.     {  
  12.         cout<<"这是A类"<<endl;  
  13.     }  
  14.   
  15. };  


           b.h:

[html] view plaincopy
  1. #include <iostream>  
  2. #include "a.h"  
  3.   
  4. using namespace std;  
  5. class b  
  6. {  
  7. public:  
  8.     a ia;  
  9.     void putB()  
  10.     {  
  11.         cout<<"这是B类"<<endl;  
  12.     }  
  13.   
  14. };  


          主函数

[html] view plaincopy
  1. #include <stdio.h>  
  2. #include <tchar.h>  
  3. #include "b.h"  
  4. int _tmain(int argc, _TCHAR* argv[])  
  5. {  
  6.       
  7.     b B;  
  8.     B.putB();  
  9.   
  10.     B.ia.putA();  
  11.   
  12.       
  13.        
  14.   
  15.     getchar();  
  16.     return 0;  
  17. }  
参考资料:http://blog.csdn.net/tianshuai11/article/details/7705321
原创粉丝点击