最近在课堂上教我们对STL迭代通过列表来遍历。在给出链表的基本迭代器的示例代码中,我遇到了一些我无法理解的东西。理解迭代器类在C++
我们得到了2迭代类,常量性迭代器。他们都是List类的子类。迭代器从const_iterator继承。在迭代器的构造函数中,我不确定为什么它是这样写的;
迭代器类:
class iterator:public const_iterator{
friend sortedList
protected:
iterator(Node* n):const_iterator(n){}
public:
iterator(){
n = nullptr;
}
的常量性类:
class const_iterator {
friend SortedList
protected:
Node* curr_;
const_iterator(Node* n){
curr_ = n;
}
public:
const_iterator(){
curr_ = nullptr;
}
我的问题是,为什么迭代器常量性继承和为什么迭代器的构造函数初始化的const_iterator构造函数和无为本身。
方的问题;当从迭代器访问curr_时,我会如何引用它?我只是打电话curr_或我会使用this-> curr_?
这不是标准库的代码。为了理解它,我们需要看到更多关于你所要求的任何实现。 –
无论如何,'iterator'中的default-ctor看起来破损。 – Deduplicator
你可以看看https://stackoverflow.com/questions/2844466/can-iterator-type-just-subclass-const-iterator,可以帮助您了解从常量性继承的理由。我个人不喜欢这样做,因为IMO公共继承应该用来传达一个'公共的'信息(即模型是一个 - 将会多态使用的对象的关系),这里不是这种情况。 –