2011-11-16 55 views
1

我有一個一流的設計問題,可能與這個例子簡化:C++:父指針類,包含孩子

// 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會員的每次電話會議?

+0

我還沒做C++。但似乎你必須將父指針傳遞給你的類。您可以創建一個名爲parent的屬性併爲其分配父指針。 – Frank

+0

@Frank:問題是編譯器中的循環依賴。傳遞父指針並不是這裏棘手的部分。 –

回答

9

你並不需要包括該文件,如果你只使用一個指針,你不會有循環的麻煩,如果你將它們包含在.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" 

雖然你可能是通過重新考慮您的設計更好。

+1

非常感謝!我一直在努力解決這個問題! –

3

向前聲明是朋友:

// 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; 
} 
+0

啊,捱打吧=) – zyndor

2

您應該使用前置聲明,並在您的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 
0

使用forward declaration的頭文件來告訴編譯器foo2是一個將在隨後定義的類。

class foo2; 

class foo { 
    foo2 *child; 
}; 

class foo2 { 
    foo *parent; 
};