为迭代器编写解引用操作符
Writing a dereference operator for iterator
我正在编写一个Set类,以便了解它们的实际工作方式,并尝试编写我自己的迭代器。据我所知,迭代器只是一个抽象的高级指针,通过一个结构体进行迭代。
话虽如此,我知道迭代器的重要部分是++——和*操作。我已经成功地创建并测试了in/递减操作符,但是在定义服从Iterator时需要返回什么时,我花了很多时间。
返回它所指向的对象吗?
下面是我的set.h文件中的相关代码:class Set{
private:
struct Elem {
ELEMENT_TYPE info;
Elem *prev, *next;
};
Elem *_head, *_tail;
int _size;
public:
//...
class Iterator{
private:
Elem * _cur;
public:
Iterator(){}
Iterator( Elem* );
Iterator operator++( int );
Iterator operator++();
Iterator operator--( int);
Iterator operator--();
bool operator==( const Iterator& rhs );
bool operator!=( const Iterator& rhs );
Elem operator*();
};
//...
};
就像我说的,我返回的是迭代器指向的"Elem",对吗?
Set::Elem* Set::Iterator::operator*(){
return _cur;
}
通常通过引用返回指向的元素。
Elem& operator*() { return *_cur; }
不过,它在一定程度上取决于迭代器的类型。某些迭代器(例如输入迭代器)不一定返回引用。
您通常会返回一个引用,如:
ELEMENT_TYPE & operator*() { return _cur->info;}
*
操作符应该返回值或引用
Set::Elem &Set::Iterator::operator*() {
return *_cur;
}
const Set::Elem &Set::Iterator::operator*() const {
return *_cur;
}
相关文章:
- 清楚地说明 * 和 & 作为类型的一部分和作为取消引用/address_of操作符之间的区别
- 对友元操作符的未定义引用
- 将代码声明放入字中(引用操作符和解引用操作符混淆)
- 如何在c++中重载=操作符来通过引用进行复制
- 带引用类成员的赋值操作符
- 如何使操作符[]返回对unsigned int中单个位的引用
- 强制转换操作符重载和引用
- 下标操作符重载:返回引用问题
- 在操作符[]前解引用成员指针
- 解引用操作符(*)作为类的成员函数重载时是如何工作的?
- 返回值的引用操作符
- c++ std::map::iterator一无所获,但下标操作符返回对映射值的引用
- 操作符重载在没有引用的情况下可以工作吗?
- 为什么c++中通过引用传递的形参不需要解引用操作符
- 关于C/ c++解引用操作符
- 看起来像一个引用操作符,但不是c++定义
- 为迭代器编写解引用操作符
- 理解引用和解引用操作符
- 编译器添加引用操作符
- 解引用操作符和endl没有输出