In C ++, the two classes reference each other's solution and reference the solution.
I. Problem Description
Now there are two classes A and B that need to be defined. B is required for defining A and A is required for defining B.
Ii. Analysis
Definitions and calls of A and B are definitely not allowed in A single file, which will lead to an endless loop of two loop calls.
The root cause is: when defining A, B exists in A, so you need to check the space occupied by B. However, you need to know the space occupied by, causes an endless loop.
Solution:
(1) write two header files A. h and B. h to declare Class A and B respectively;
(2) write two. cpp files to define classes A and B respectively;
(3) import the header file of B into the header file of;
(4) do not import the header file of A in the header file of B, but declare Class A in the form of extern. In addition, use A pointer when using A in B.
Principle:When calling A with A pointer in B, when A needs to know the size of space occupied by B, it will find the definition file of B, although the definition file of B does not import the header file of A and does not know the space occupied by A, the pointer format used when B calls A is, B only knows that the pointer occupies 4 bytes and does not need to know the actual space occupied by A. That is to say, A also knows the space occupied by B.
III. C ++ example
A header file A. h:
# Ifndef _ A # define _ A <strong> # include "B. h "// the header file of A imports the header file of B </strong> // extern class B; class A {private: int a; B objectb; // The header file of A imports the header file of B. When calling B, the pointer public: A (); int geta (); void handle ();}; # endif _
B header file B .h:
# Ifndef _ B # define _ B <strong> // # include "A. h" // the header file of B is not imported into the header file of A. There are three points to note! Extern class A; // Note 1: Use extern to declare A </strong> class B {private: int B; A * objecta; // NOTE 2: when calling A, you need to use the pointer public: B (); int getb (); void handle () ;}; # endif _ B
Definition file A. cpp of:
#include <iostream><strong>#include "A.h"</strong>using namespace std;A::A(){this->a=100;}int A::geta(){return a;}void A::handle(){cout<<"in A , objectb.b="<<objectb.getb()<<endl;}
Definition file B. cpp:
# Include <iostream> <strong> # include "B. h "# include". h "// Note 3: in B. import the header file of A in cpp </strong> using namespace std; B: B () {this-> B = 200;} int B: getb () {return B;} void B: handle () {objecta = new A (); cout <"in B, objecta-> a = "<objecta-> geta () <endl ;}
Main. cpp:
# Include <iostream> # include <cstdlib> <strong> # include ". h "// # include" B. h "// because. h already contains B. h, so you do not need to import B. h. </Strong> using namespace std; void main () {A; a. handle (); B B; B. handle (); system ("pause ");}
Running result:
4. Note
Compilation fails in the following cases:
A. h contains B. h and B. h contains A. h.