【发布时间】:2017-05-10 12:51:19
【问题描述】:
我有一个任务,我需要在其中创建模板类 LinkedList 和 Traversible。类 Traversible 需要是一个接口,它声明了一些集合类的索引和迭代函数。我不完全知道如何为迭代器制作接口,以便 LinkedList 可以使用它。我在想类似的东西
template <class T, class U>
class ITraversible {
public:
virtual U begin() noexcept = 0;
virtual U end() noexcept = 0;
virtual T& operator[](int) = 0;
};
然后在 LinkedList 头文件中我会这样做:
template <class T>
class LinkedList : public ITraversible<T,typename LinkedList<T>::iterator> {
struct node {
T data;
node* next, *prev;
explicit node(const T&);
void connect(node*);
};
node *head, *tail;
int n;
public:
/*************************ITERATOR************************/
class iterator : public std::iterator<std::bidirectional_iterator_tag, node*> {
typename LinkedList<T>::node* itr;
explicit iterator(node*) noexcept;
friend class LinkedList;
public:
iterator& operator++();
iterator operator++(int);
iterator& operator--();
iterator operator--(int);
bool operator==(const iterator&) const noexcept;
bool operator!=(const iterator&) const noexcept;
T& operator*() const noexcept;
T& operator->() const noexcept;
};
/**********************************************************/
LinkedList() noexcept;
LinkedList(std::initializer_list<T>);
LinkedList(const LinkedList&);
LinkedList(LinkedList&&) noexcept;
~LinkedList() noexcept;
LinkedList& operator=(LinkedList) noexcept;
template <class A>
friend void swap(LinkedList<A>&, LinkedList<A>&);
void add(const T&);
void removeAt(int);
int size() const noexcept;
bool operator==(const LinkedList&) const noexcept;
bool operator!=(const LinkedList&) const noexcept;
virtual T& operator[](int) override;
virtual iterator begin() noexcept override;
virtual iterator end() noexcept override;
};
但是 Traversable 模板有两个参数,它应该只有一个。 这是我应该做的吗?请记住,我是模板和迭代器的新手。
【问题讨论】:
-
为什么你认为 Traversible 模板必须有一个参数?
-
在分配中说我们需要编写类 Traversable
标签: c++ templates interface iterator