簡體   English   中英

從類訪問類中的類對象

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM