繁体   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