c++迭代器:没有合适的默认构造函数可用
C++ Iterator: no appropriate default constructor available
我试图实现自定义迭代器链表。我得到了一堆错误试图实现复制构造函数:
'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());
}
相关文章:
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 初始化具有非默认构造函数的std::数组项的更好方法
- 具有默认模板类型的默认构造函数的类型推导
- 如何使用非默认构造函数实例化模板化类
- 有没有一种代码密度较低的方法来使用非默认构造函数初始化数组?
- 声明没有默认构造函数的字段
- 没有默认构造函数作为模板参数的自定义比较器
- C++17 没有默认构造函数的地图放置(私有默认构造函数)
- 使用移动调用对等构造函数unique_ptr默认构造函数
- C++复制构造函数和默认构造函数
- 将向量从 N1 缩小到 N2 项,而不触发默认构造函数并仅使用 move 语义
- 为什么即使我调用参数化构造函数也会调用默认构造函数?
- 具有非默认构造函数的单例类
- 在 C++ 中声明 const 对象需要用户定义的默认构造函数.如果我有一个可变成员变量,为什么不呢?
- 如何处理没有默认构造函数但在另一个构造函数中构造的对象?
- 在C++中使用默认构造函数初始化对象的不同方法
- 在没有默认构造函数的情况下创建的派生对象
- 强制使用默认构造函数对成员进行未初始化的声明
- 使用默认构造函数初始化对象的不同方法
- 创建类类型的动态分配数组,其中类不得具有默认构造函数