Circular references in C++ in different files

2019-07-13 06:10发布

问题:

If i want a circular reference but in two different files in C++, how would I implement that?

For example

AUnit.h

#inclue <BUnit.h>
class AClass : public TObject
{

   __published
        BClass * B;
};

BUnit.h

#include <AUnit.h>
class BClass : public TObject
{
    __published
        AClass *A;     
};

I can't make it in only one file with forward declarations.

回答1:

I assume you're talking about circular dependencies.

The answer is indeed to use a forward declaration, such as:

AUnit.h

#include <BUnit.h>
class AClass : public TObject
{
   BClass *B;
};

BUnit.h

class AClass;  // Forward declaration

class BClass : public TObject
{
   AClass *A;
};

You could even have a forward declaration in both header files, if you wanted.



回答2:

You can use forward declaration in this case too:

// AUnit.h
class BClass;
class AClass : public TObject
{

   __published
        BClass * B;
};

// BUnit.h
#include <AUnit.h>
class BClass : public TObject
{
    __published
        AClass *A;     
};

There is no difference to the scenario if they are both in one file, because #include does nothing but inserting the included file (it is really jut text-replacement). It is exactly the same. After preprocessing of BUnit.h, the above will look like this:

class BClass;

class AClass : public TObject
{

   __published
        BClass * B;
};

class BClass : public TObject
{
    __published
        AClass *A;     
};