The policies of two classes in C ++
I. Problem Description
Class A contains class B instances, and Class B also contains class A instances.
Ii. solution strategies
1) solution to errors
File A contains file B, and file B contains file A, which forms an endless loop.
[Html]
# Include "B. h"
Class
{
Int I;
B B;
};
# Include "A. h"
Class B
{
Int I;
A;
};
2) correct writing and precautions
1) The main function only needs to contain B. h, because B. h contains a. h.
2) class B does not need to be included in a.h, but must be declared. B is also successfully referenced while avoiding endless loops.
3) include class B but not the header file "B. h". In this way, only pointer of type B can be declared !!!! It cannot be instantiated !!!!
A.h:
[Html]
# Include <iostream>
Using namespace std;
Class B;
Class
{
Public:
B * ib;
Void putA ()
{
Cout <"this is A class" <endl;
}
};
B .h:
[Html]
# Include <iostream>
# Include "a. h"
Using namespace std;
Class B
{
Public:
A ia;
Void putB ()
{
Cout <"This is B type" <endl;
}
};
Main Function
[Html]
# Include <stdio. h>
# Include <tchar. h>
# Include "B. h"
Int _ tmain (int argc, _ TCHAR * argv [])
{
B B;
B. putB ();
B. ia. putA ();
Getchar ();
Return 0;
}