Solution for mutual reference between two classes in C ++
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 _# Include "B. h" // the header file of A imports the header file of B.// Extern class B; class A {private: int a; B objectb; // the header file of class A imports the header file of class B. When calling class B, you do not need to use the public pointer: A (); int geta (); void handle () ;};# endif _
B header file B .h:
# Ifndef _ B # define _ B/// # Include "A. h" // the header file of B does not import the header file of A. There are three points to note! Extern class A; // Note 1: Use extern to declareClass B {private: int B; A * objecta; // NOTE 2: when calling A, use the public: B (); int getb (); void handle () ;};# endif _ B
Definition file A. cpp of:
# Include
# Include "A. h"Using namespace std; A: A () {this-> a = 100;} int A: geta () {return a;} void A: handle () {cout <"in A, objectb. B = "<
Definition file B. cpp:
# Include
# Include "B. h" # include "A. h" // Note 3: import the header file of A in B. cpp.Using namespace std; B: B () {this-> B = 200;} int B: getb () {return B;} void B: handle () {objecta = new A (); cout <"in B, objecta-> a =" <
Geta () <
Main. cpp:
# Include
# Include
# Include "A. h" // # include "B. h" // because A. h already contains B. h, you do not need to import B. h here.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.