您没有operator++
为 Node 类实现;你为迭代器实现它。迭代器类应该是一个单独的类。
并且请不要通过做出假设来破坏您的模板(因为val
是 a T
,您的构造函数应该接受 a T
,而不是 a int
)。另外,不要int
像这样忽略 operator++ 的参数:它是一个用于区分前置增量实现和后置增量实现的伪参数。
template <typename T>
struct Node {
T val;
Node *next;
Node(const T& t = T()) : val(t) {}
};
template <typename T>
struct node_iter {
Node<T>* current;
node_iter(Node<T>* current): current(current) {}
const node_iter& operator++() { current = current->next; return *this; }
node_iter operator++(int) {
node_iter result = *this; ++(*this); return result;
}
T& operator*() { return current->val; }
};
int main() {
// We make an array of nodes, and link them together - no point in
// dynamic allocation for such a simple example.
Node<int> nodes[10];
for (int i = 0; i < 10; ++i) {
nodes[i] = Node<int>(i);
nodes[i].next = (i == 9) ? nodes + i + 1 : 0;
}
// we supply a pointer to the first element of the array
node_iter<int> test(nodes);
// and then iterate:
while (test.current) {
cout << *test++ << " ";
}
// Exercise: try linking the nodes in reverse order. Therefore, we create
// 'test' with a pointer to the last element of the array, rather than
// the first. However, we will not need to change the while loop, because
// of how the operator overload works.
// Exercise: try writing that last while loop as a for loop. Do not use
// any information about the number of nodes.
}
这距离提供适当的数据封装、内存管理等还有很长的路要走。制作一个适当的链表类并不容易。这就是标准库提供一个的原因。不要重新发明轮子。