c++迭代器:没有合适的默认构造函数可用

C++ Iterator: no appropriate default constructor available

本文关键字:默认 构造函数 迭代器 c++      更新时间:2023-10-16

我试图实现自定义迭代器链表。我得到了一堆错误试图实现复制构造函数:

'LinkedListIterator>':没有合适的默认构造函数可用' linkedlistterator> LinkedList::begin(void)':无法将'this'指针从'const LinkedList'转换为'LinkedList &;'' linkedlistterator> LinkedList::end(void)':无法将'this'指针从'const LinkedList'转换为'LinkedList &'

LinkedList

class LinkedList
{
std::unique_ptr<node> head;
std::unique_ptr<node> tail;
LinkedList(const LinkedList& other)
{
    init();
    iterator i = other.begin();
    while (i != other.end())
        add(*i++);
    head = other.head;
    tail = other.tail;
}
iterator begin() 
{
    return iterator(head->next);
}
iterator end()
{
    return iterator(tail);
}
迭代器

template <typename TNode>
class LinkedListIterator
{
    friend class LinkedList<typename TNode::value_type>;
    TNode* p;
public:
    LinkedListIterator(TNode* p) : p(p) {}
    LinkedListIterator(const LinkedListIterator& other) : p(other.p) {}
    LinkedListIterator& operator=(LinkedListIterator other) { std::swap(p, other.p); return *this; }
    void operator++() { p = p->next; }
    void operator++(int) { p = p->next; }
    bool operator==(const LinkedListIterator& other) { return p == other.p; }
    bool operator!=(const LinkedListIterator& other) { return p != other.p; }
    int& operator*() { return p->data; }
    LinkedListIterator<TNode> operator+(int i)
    {
        LinkedListIterator<TNode> iter = *this;
        while (i-- > 0 && iter.p)
        {
            ++iter;
        }
        return iter;
    }
};
}

让我知道如果你需要我张贴更多的代码。谢谢。

成员函数begin()end()定义为非常数成员函数

iterator begin() 
{
    return iterator(head->next);
}
iterator end()
{
    return iterator(tail);
}

但是你调用const对象other

LinkedList(const LinkedList& other)
{
    init();
    iterator i = other.begin(); // <== here
    while (i != other.end()) // <== here
        add(*i++);
    head = other.head;
    tail = other.tail;
}

对于错误信息

没有合适的默认构造函数

则看不到在哪里使用了默认构造函数。尽管如此,错误信息是足够清楚的:类LinkedListIterator<Node<T>>没有默认构造函数,但在代码的某些地方,您使用默认构造函数创建了该类型的对象。

假设'iterator'被定义为' linkedlisttiterator ',那么您似乎正在尝试将'head'和'tail'变量(似乎是全局的?)传递给不存在的构造函数,并且编译器正在做最后的努力来匹配复制构造函数(对于没有匹配)。

我认为代码应该如下所示:
iterator begin() 
{
    return iterator(head->next.get());
}
iterator end()
{
    return iterator(tail.get());
}