gpt4 book ai didi

C++——使用嵌套类中的类元素?

转载 作者:行者123 更新时间:2023-11-28 03:32:30 25 4
gpt4 key购买 nike

好吧,我有一个类 LinkedList,它有一个嵌套类 LinkedListIterator。在 LinkedListIterator 的方法中,我引用了 LinkedList 的私有(private)字段。我认为这是合法的。但是我得到了错误:

from this location

每次我引用它们时。

我在封闭类的字段上得到相应的错误消息:

invalid use of non-static data member 'LinkedList<int>::tail'

知道为什么吗?相关代码如下:

template<class T>
class LinkedList {

private:
//Data Fields-----------------//
/*
* The head of the list, sentinel node, empty.
*/
Node<T>* head;
/*
* The tail end of the list, sentinel node, empty.
*/
Node<T>* tail;
/*
* Number of elements in the LinkedList.
*/
int size;

class LinkedListIterator: public Iterator<T> {

bool add(T element) {

//If the iterator is not pointing at the tail node.
if(current != tail) {

Node<T>* newNode = new Node<T>(element);
current->join(newNode->join(current->split()));

//Move current to the newly inserted node so that
//on the next call to next() the node after the
//newly inserted one becomes the current target of
//the iterator.
current = current->next;

size++;

return true;
}

return false;
}

最佳答案

您不能像那样只使用非static 成员。我认为以下示例可以解决问题:

LinkedList<int>::LinkedListIterator it;
it.add(1);

方法中的 currenttail 是什么?没有 LinkedList 的实例可言,因此这些成员甚至还不存在。

我并不是说让成员static,那是错误的,但请重新考虑您的方法。

研究 std 迭代器是怎样的。

关于C++——使用嵌套类中的类元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12085683/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com