Reprinted from --- "https://blog.csdn.net/xiqingnian/article/details/41214539
I. Description of the problem
There are two classes A and B need to be defined, when the need to use the definition of A B, B when the need to use the definition of A.
Second, analysis
A and B both define and call in a document is certainly not possible, this will cause an infinite loop cycle two calls.
The fundamental reason is: A definition of the time, there are A B, so we need to see the B accounts for space, but also found time to see the need to know the A accounts for space, resulting in an endless loop.
Solution:
(1) Write two headers Ah and Bh are used to declare classes A and B;
(2) Write .cpp files are used to define the two classes A and B;
(3) into the header in the header file B in A;
(4) A file header is not introduced in the header file B, but using extern manner declaring class A, and, B is used when A is in the form of pointers to use.
Principle: In pointer with B calls A, B then A needs to know the size of the space and they will go to find the definition file B, although the definition file B and A did not import the header file, do not know the A accounts space, but due to time in B calls a pointer form with a, B only know the pointer 4 bytes can be, do not need to know the size of the space a really, that is, a B also know the size of the space of.
I understand - "One must have a pointer through a pointer (4 bytes) + extern declaration of way, to ensure that, when compiled Bh, and through; so at compile time Ah, directly by the
Three, C ++ examplesA header file of Ah:
-
-
-
<strong>
-
//extern class B;
-
-
class A
-
{
-
private:
-
int a;
-
B objectB; header file // A head import file B, B when the call can not pointer
-
-
public:
-
A();
-
you geta () ;
-
void handle();
-
};
-
-
B header files Bh:
-
-
-
-
<strong> // # the include "Ah" B // A header file does not import header files, you need to have three things to note!
-
extern class A ; // NOTE 1: extern statement needed A </ strong>
-
-
class B
-
{
-
private :
-
int b;
-
* ObjectA A; // Note 2: A call when the need to use a pointer
-
public :
-
B();
-
int getb () ;
-
void handle();
-
};
-
-
A definition file of A.cpp:
-
-
<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;
-
}
B's definition file B.cpp:
-
-
<strong>
-
-
-
using namespace std;
-
-
B::B()
-
{
-
this->b= 200;
-
}
-
-
int B::getb()
-
{
-
return b;
-
}
-
-
void B::handle()
-
{
-
objects = new A ();
-
cout<< "in B , objecta->a="<<objecta->geta()<< endl;
-
}
main.cpp:
-
-
-
<strong>
-
// # include "Bh" // because Ah which already contains Bh, so this does not need to import the Bh. </ Strong>
-
-
using namespace std;
-
-
void main ()
-
{
-
A a;
-
a.handle();
-
B b;
-
b.handle();
-
-
system( "pause");
-
}
-