parent指针,指向包含子类的类
C++: parent pointer to class that includes the child
我有一个类设计问题,可以用这个例子来简化:
// 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;
};
相关文章:
- 继承期间显示未知行为的子类
- 通过指向指针数组的指针访问子类的属性
- 从父类方法返回子类对象
- 如果基类包含双指针成员,则派生类的构造函数
- c++, 在子类中,如何在没有对象的情况下访问父类的方法?
- 将父类对象强制转换为子类的问题
- C++ - 是否可以让子类按值包含包含类?
- 当子类需要在 c++ 中相互包含时,继承有缺陷
- C++11 向量包含 2 个不同的子类,但不能同时进行
- C ,基础课程如何将子类作为成员包含并调用其方法
- C++:从两个包含子类 (typedef) 的列表创建一个列表
- 如何让子类包含指向基类的指针
- 如何创建一个包含C 中的子类的类的链接列表
- C++中包含父类对象的子类有什么问题(如果有的话)
- C++传递包含子类元素的类列表
- 父类包含子类C++的静态实例
- parent指针,指向包含子类的类
- 我是否应该在将实现委托给子类的类中包含成员定义?
- 子类包含基类使用的静态成员
- 具有包含另一个类的对象的数组的子类的构造函数