C++ two class header files include each other

When constructing your own class, you may encounter the problem of mutual reference between two classes, for example: class A class B is defined, A uses the type defined by B, and B also uses the type defined by
A A
{
    int i;
    B b;
}


class B
{
    int i;
    A* a;
}


Please pay attention to the content of the above definition, in general, class A cannot appear, and class B defines objects by mutual reference, that is, as follows:
class A
{
  int i;
  B b;
}


class B
{
  int i;
  A a;
}
In this case, think that there can be ababababab…………, it is very kind of endless descendants, then my machine is also unbearable. The main thing is that this relationship is difficult to exist and difficult to manage. This definition is similar to an infinite loop in a program. So, generally speaking, at least one of the definitions of the two uses pointers, or both use pointers, but never both define entity objects.


Closer to home, then, when defining, because of mutual reference, header files will definitely need to be included with each other. If you just include each other's header files in their respective header files, it will not pass the compilation, as follows:
//class Ah
#include "Bh"
class A
{
  int i;
  B b;
}


//class Bh
#include "Ah"
class B
{
  int i;
  A *a;
}

The above inclusion method may cause the compiler to have an error message: the Ah file uses the notification Type B.
How to do?
The general practice is: among the header files of the two classes, choose one that contains the header file of the other class, but the other header file can only use the declaration form of class *;, and in the implementation file (*.cpp) Include the header file as follows:
//class Ah
#include "Bh"
class A
{
  int i;
  B b;
}

//class Bh
class A;
class B
{
  int i;
  A *a;
}

//B.cpp
/ / The following statement should be required at the file inclusion in B.cpp, otherwise, any content of member a cannot be called
#include "Ah"
B::B()
{
……
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324691152&siteId=291194637