C++中两个类互相引用的解决方法

转载自  ---》 https://blog.csdn.net/xiqingnian/article/details/41214539

一、问题描述

现在有两个类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的占空间大小的。

我的理解--》必须得其中一个是指针,通过指针(4字节) + extern 声明的方式,来保证编译B.h的时候,能通过;这样在编译A.h的时候,直接就可以通过了

三、C++示例

A的头文件A.h:

  1. #ifndef _A
  2. #define _A
  3. <strong>     #include "B.h"//A的头文件导入了B的头文件</strong>
  4. //extern class B;
  5. class A
  6. {
  7. private:
  8. int a;
  9. B objectb; //A的头文件导入了B的头文件,在调用B的时候就可以不用指针
  10. public:
  11. A();
  12. int geta();
  13. void handle();
  14. };
  15. #endif _A


B的头文件B.h:

  1. #ifndef _B
  2. #define _B
  3. <strong> //#include "A.h"//B的头文件没有导入A的头文件,需要有三个地方需要注意!
  4. extern class A; //注意1:需要用extern声明A</strong>
  5. class B
  6. {
  7. private:
  8. int b;
  9. A* objecta; //注意2:调用A的时候需要用指针
  10. public:
  11. B();
  12. int getb();
  13. void handle();
  14. };
  15. #endif _B


A的定义文件A.cpp:

  1. #include <iostream>
  2. <strong> #include "A.h"</strong>
  3. using namespace std;
  4. A::A()
  5. {
  6. this->a= 100;
  7. }
  8. int A::geta()
  9. {
  10. return a;
  11. }
  12. void A::handle()
  13. {
  14. cout<< "in A , objectb.b="<<objectb.getb()<< endl;
  15. }


B的定义文件B.cpp:

  1. #include <iostream>
  2. <strong> #include "B.h"
  3. #include "A.h"//注意3:在B.cpp里面导入A的头文件</strong>
  4. using namespace std;
  5. B::B()
  6. {
  7. this->b= 200;
  8. }
  9. int B::getb()
  10. {
  11. return b;
  12. }
  13. void B::handle()
  14. {
  15. objecta= new A();
  16. cout<< "in B , objecta->a="<<objecta->geta()<< endl;
  17. }


main.cpp:

  1. #include <iostream>
  2. #include <cstdlib>
  3. <strong> #include "A.h"
  4. //#include "B.h" //因为A.h里面已经包含B.h,所以在此不需要导入B.h了。</strong>
  5. using namespace std;
  6. void main()
  7. {
  8. A a;
  9. a.handle();
  10. B b;
  11. b.handle();
  12. system( "pause");
  13. }

猜你喜欢

转载自blog.csdn.net/qq_34326603/article/details/80995143