簡體   English   中英

我制作了一個包含迭代器和節點類的列表,但由於某種原因,迭代器 class 沒有使列表 class 成為朋友

[英]Im making a list with iterators and node classes nested in it but for some reason the iterator class is not making the list class a friend

 template <class T>
class List
{
class Node
{
public:
    Node()
    {
        next = 0;
        data = 0;
    }
    Node* next;
    T data;
};
Node* head = new Node;
Node* tail = new Node;
int size = 0;
public:
class Iterator
{
 Node* curr;
    friend class List<T>;
public:
 Iterator()
    {
        curr = nullptr;
    }
    friend void fun()
    {
        cout << "helloworld" << endl;
    }
    Iterator begin()
    {
        Iterator it(head->next);
        return it;
    }
};
};

創建了另外兩個 class 的塊和程序,程序包含塊列表。 實現了易於使用的迭代器,但無法通過列表 class 訪問其公共和私有成員。

int main()
{
List<int> l1;
List<int>::Iterator it;
it = l1.begin();
fun();//iterator befriending neither class nor function
}

錯誤是:class 列表沒有成員開始 E0135 開始:不是 class 列表的成員 C2039 在 vs22

在您的main函數中,您聲明了一個List<int>和一個List<int>::Iterator 你在哪里打電話begin() l1上,這是一個List<int>

List<int> l1;
List<int>::Iterator it;
//   VV -> That's the List<int>
it = l1.begin();

List<int>是否有begin()的定義? 不,這個 function 在List<int>::Iterator中定義。

我想你在這里對friend的含義有誤解。 這意味着,允許朋友 class (在這種情況下為List<T> )訪問 class (在這種情況下為Iterator )的privateprotected成員。

不會使List<T>::headIterator中神奇地可用。 不會使Iterator::beginList<T>的實例上可訪問。


我建議進行以下小改動:將begin的聲明從Iterator移動到List<T>並為Iterator提供適當的構造函數。 然后,您可以刪除任何朋友聲明,因為它們不是必需的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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