parent指针,指向包含子类的类

C++: parent pointer to class that includes the child

本文关键字:子类 包含 指针 parent      更新时间:2023-10-16

我有一个类设计问题,可以用这个例子来简化:

// foo.h
#include "foo2.h" 
class foo
{
public:
    foo2 *child;
// foo2 needs to be able to access the instance
// of foo it belongs to from anywhere inside the class
// possibly through a pointer
};
// foo2.h
// cannot include foo.h, that would cause an include loop
class foo2
{
public:
    foo *parent;
// How can I have a foo pointer if foo hasn't been pre-processed yet?
// I know I could use a generic LPVOID pointer and typecast later
// but isn't there a better way?
};

除了使用泛型指针或将父指针传递给每次调用foo2成员之外,还有其他方法吗?

如果您只使用指针,则不需要包含该文件,如果将它们包含在.cpp文件中,则不会出现循环问题:

// foo.h
class foo2; // forward declaration
class foo
{
public:
    foo2 *child;
};
// foo2.h
class foo;
class foo2
{
public:
    foo *parent;
};
//foo.cpp
#include "foo.h"
#include "foo2.h"
//foo2.cpp
#include "foo2.h"
#include "foo.h"

尽管重新考虑你的设计可能会更好。

前向声明是友元:

// foo.h
class foo2;
class foo
{
  foo2 *pFoo2;
};
// foo2.h
#include "foo.h"
class foo2
{
  foo *pFoo;
};

正如Pubby所说,需要相互了解的类可能只是一个类,或者可能是一个类,有两个成员,这两个成员都知道父类,但不是双向关系。

关于为人父母和成为一般人:

template  <class Parent>
class  ChildOf
{
public:
  // types
  typedef Parent  ParentType;
  // structors
  explicit ChildOf(Parent& p);
  ~ChildOf();
  // general use
  Parent&  GetParent();
  const Parent&  GetParent() const;
  void  SetParent(Parent& p);
private:
  // data
  Parent  *m_pParent;
};
/*
  implementation
*/
template  <class ParentType>
ChildOf<ParentType>::ChildOf(ParentType& p)
: m_pParent(&p)
{}
template  <class Parent>
ChildOf<Parent>::~ChildOf()
{}
template  <class ParentType>
inline
ParentType&  ChildOf<ParentType>::GetParent()
{
  return *m_pParent;
}
template  <class ParentType>
inline
const ParentType&  ChildOf<ParentType>::GetParent() const
{
  return *m_pParent;
}
template  <class ParentType>
void  ChildOf<ParentType>::SetParent(ParentType& p)
{
  m_pParent = &p;
}

您应该使用前向声明并在您的cpp

中包含头文件。
// foo.h
#ifndef FOO_H_
#define FOO_H_
class foo2;
class foo
{
public:
    foo2 *child;
};
#endif
// foo2.h
#ifndef FOO_2_H_
#define FOO_2_H_
class foo;
class foo2
{
public:
    foo *parent;
};
#endif

使用前向声明告诉编译器foo2是一个将在随后定义的类。

class foo2;
class foo {
    foo2 *child;
};
class foo2 {
    foo *parent;
};