Circular references in C++ in different files

末鹿安然 提交于 2020-01-04 07:28:11

问题


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


来源:https://stackoverflow.com/questions/6444071/circular-references-in-c-in-different-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!