【发布时间】:2020-08-27 07:10:55
【问题描述】:
我是一个初学者,现在我正在尝试实现包含函数 begin() 的类链表。 该函数很好地返回列表中的第一个元素,但我想做的是在下一个位置返回迭代器,例如这样的:
List<int>::iterator iter2 = a.begin() + 2; // or iter2 = iter2 + 1;
cout <<iter2->data;
输出是垃圾,例如 21213123..
所以在这里我想我应该使用运算符重载+,这是我的函数:
template<class T>
Node<T>* operator+(const Node<T>& iter, const int& pos)
{
cout << "in"; for testing, but seems that doesnt even entry here
return NULL;
}
那么谁能帮助我?非常感谢
P.S:这里是类节点
template<class T>
class Node {
public:
T data;
Node* next;
Node() :data(0), next(NULL) {}
Node(T val, Node<T>* pointer = NULL) :data(val), next(pointer) {}
};
和列表类
template<class T>
class List {
public:
typedef Node<T>* iterator;
typedef const Node<T>* const_iterator;
//constructors
List() { item = NULL; counter = 0; }
explicit List(int val) :counter(1) { item = new Node<T>(val); }
~List() { // to be made
}
//public functions
int size() { return counter; }
iterator begin() {
return item;
}
iterator end()
{
iterator last = item;
while (last->next != NULL)
{
last = last->next;
}
return last;
}
void push_front(const int& val) {
iterator newNode = new Node<T>(val, item);
item = newNode;
counter++;
}
void append(const int& val)
{
iterator newnode = new Node<T>(val);
newnode->next = NULL;
iterator last = item;
if (item == NULL)
{
item = newnode;
return;
}
while (last->next != NULL)
last = last->next;
last->next = newnode;
counter++;
}
int operator[](const int&);
private:
iterator item;
int counter;
};
【问题讨论】:
-
cout被缓存了,试试把` -
请提供minimal reproducible example。您实现的运算符是用于
Node而不是iterator? -
它不起作用..
-
还要注意,
iterator不应该是指针类型,除非存储是连续的,比如向量 -
我们可以看看你的
begin函数的实现吗?这将有助于确定正在发生的事情。
标签: c++ linked-list operator-overloading operator-keyword