我想定义后续代码以便能够像这样使用它 "for (auto x:c0){ printf("%i ",x); }"
但是我有一点不明白,我已经搜索了一段时间。
我得到的错误是: 错误:一元‘*’的无效类型参数(有‘CC::iterator {aka int}’)
#include <stdio.h>
class CC{
int a[0x20];
public: typedef int iterator;
public: iterator begin(){return (iterator)0;}
public: iterator end(){return (iterator)0x20;}
public: int& operator*(iterator i){return this->a[(int)i];}
} ;
int main(int argc, char **argv)
{ class CC c0;
for (auto x:c0){
printf("%i ",x);
}
printf("\n");
return 0;
}
最佳答案
您似乎正在尝试使用 int
当您使用成员 operator*()
进行迭代时作为尊重操作。那行不通:
operator*()
您定义的是二元运算符(乘法)而不是一元取消引用运算。- 您不能为内置类型重载运算符,迭代器类型需要有解引用运算符。
为了能够使用基于范围的 for
你需要创建一个前向迭代器类型,它需要几个操作:
- 生命周期管理,即复制构造函数、复制赋值和销毁(通常生成的就足够了)。
- 定位,即
operator++()
和operator++(int)
. - 值访问,即
operator*()
并且可能是operator->()
. - 有效性检查,即
operator==()
和operator!=()
.
像这样应该就足够了:
class custom_iterator {
int* array;
int index;
public:
typedef int value_type;
typedef std::size_t size_type;
custom_iterator(int* array, int index): array(array), index(index) {}
int& operator*() { return this->array[this->index]; }
int const& operator*() const { return this->array[this->index]; }
custom_iterator& operator++() {
++this->index;
return *this;
}
custom_iterator operator++(int) {
custom_iterator rc(*this);
this->operator++();
return rc;
}
bool operator== (custom_iterator const& other) const {
return this->index = other.index;
}
bool operator!= (custom_iteartor const& other) const {
return !(*this == other);
}
};
你 begin()
和 end()
然后方法将返回此迭代器的适当构造版本。您可能希望将迭代器与合适的 std::iterator_traits<...>
连接起来。但我认为使用基于范围的 for
不需要这些.
关于c++ - 如何为特殊情况定义迭代器,以便使用 auto 关键字在 for 循环中使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20730817/