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