标头声明"The chicken or the egg"



对于一个项目,我必须编写一个容器类和元素,其中元素需要了解它们所在的容器。此外,创建应该由容器中的工厂方法完成 由于如果您使用标头和 cpp 文件,这很容易,如果您(像我一样)只允许使用一个标头,对我来说似乎是不可能的。下面是问题的示例:

class myContainer;
class myElement;
class myContainer
{
  public:
    myElement *createElement()
    {
      myElement *me =new myElement(this); 
      // do some adding to list stuff
      return me;
    }
    int askMyContainer()
    {
       return 42;
    }
};
class myElement
{
  public:
    myElement(myContainer *parent)
    {
     pcontainer=parent;
    }
    int userAskingSomething()
    {
     return pcontainer->askMyContainer();
    }
 protected:
  myContainer *pcontainer;
};
类 myContainer 需要有关 myElement 的知识,这就是为什么 myElement

帽子在 myContainer 之前,但 myElement 需要有关 myContainer 的知识。

您必须将类定义和方法定义拆分为至少一个类的单独部分。

例如,首先定义myContainer类(即类及其变量/函数,而不是这些函数的实现)。然后是myElement课。接下来是 myContainer 成员函数的实际实现(如果要在头文件中使用它们,则标记为 inline)。

您可以使用其他文件拆分声明和定义来解析圆圈:

// File myContainer.h:
#include "myElement.h"
class myContainer
{
    public:
    myElement *createElement();
    int askMyContainer();
};
#include "myElement.hcc"

// File myContainer.hcc:
#include "myElement.h"
// inline myContainer functions

// File myElement.h
class myContainer;
class myElement
{
    public:
    myElement(myContainer *parent);
    int userAskingSomething();
    protected:
    myContainer *pcontainer;
};
#include "myElement.hcc"

// File myElement.hcc
#include "myContainer.h"
// inline myElement functions

在写这个问题的过程中,我有一个想法如何解决它,那就是继承。喜欢

class myContainerBase
{
  pulbic:
  int askMyContainer()
  {
     return 42;
  }
};
//...
class myElement 
{
  public:
   myElement(myContainerBase *parent)
   {
     pcontainer=parent;
   }
//...
class myContainer:public my ContainerBase
{
//...

没有人有更好的方法?或者可以吗?

Joachim Pileborg为我提供了最好的答案。在他的最后一句话中,是我以前不知道的。这是我为我们其他人提供的工作示例:-)

class myContainer;
class myElement;
class myContainer
{
  public:
    myElement *createElement();
    int askMyContainer()
    {
       return 42;
    }
};
class myElement
{
  public:
    myElement(myContainer *parent)
    {
     pcontainer=parent;
    }
    int userAskingSomething()
    {
     return pcontainer->askMyContainer();
    }
 protected:
  myContainer *pcontainer;
};

inline myElement *myContainer::createElement()
{
  myElement *me =new myElement(this); 
  // do some adding to list stuff
  return me;
}

相关内容

最新更新