[英]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
)的private
或protected
成員。
它不會使List<T>::head
在Iterator
中神奇地可用。 它不會使Iterator::begin
在List<T>
的實例上可訪問。
我建議進行以下小改動:將begin
的聲明從Iterator
移動到List<T>
並為Iterator
提供適當的構造函數。 然后,您可以刪除任何朋友聲明,因為它們不是必需的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.