开发者

Circular references in C++ in different files

开发者 https://www.devze.com 2023-03-14 14:10 出处:网络
If i want a circular reference but in two different files in C++, how would I implement that? For examp开发者_如何学Cle

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

For examp开发者_如何学Cle

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.


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;     
};


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消