[英]Accessing a class object within a class from a class
我知道這個標題有點令人困惑,但是圖表可能會有所幫助。 在一個文件中:
#ifndef ...
#def ...
#includes (including OListiterator.h>
template <class T>
class OList;
template <class T>
Class OListiterator{
friend class OList<T>::OList;
typename OList<T>::Node* iiter;
};
function defs;
#endif
在另一個:
#ifndef ...
#def ...
#includes (one is OList.h)
template<class T>
class OListiterator;
template <class T>
Class OList{
friend class OListiterator<T>::OListiterator;
public:
class Node{
};
//things
};
//functions
#endif
這就是我本人以及協助我的TA認為會起作用的方法,但是我拋出了錯誤:Node在OList中未命名類型。 有人知道我為什么/如何解決這個問題嗎? 讓我知道是否需要發布更多信息。
看起來這里有一個依賴項。 OList
需要OListIterator
,反之亦然。 解決此問題的方法是更改設計,因此不需要這種依賴性。 嘗試放置OListIterator
設計,以便可以在OList
使用它。
您需要class OList
的前向聲明:
// forward declaration
template <class T>
class OList;
template <class T>
class OListiterator{
friend class OList<T>::OList;
typename OList<T>::Node* iiter;
};
template <class T>
class OList{
friend class OListiterator<T>::OListiterator;
public:
class Node{
};
};
注意, friend class OList<T>::OList;
等效於friend class OList<T>;
因為OList<T>::OList
是在OList<T>
范圍內注入的類名。
當您將OList
的成員Node
OList
為朋友時,編譯器需要OList
的整個定義以確保有這樣的成員。
解決的辦法是打破依賴性。 為什么列表節點需要訪問列表迭代器的內部? 在我看來,應該是相反的方式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.