使用常量迭代器的运算符重载

Operator Overloading with Constant Iterators

本文关键字:运算符 重载 迭代器 常量      更新时间:2023-10-16

我有一个常量迭代器类,其中包含以下用于重载多个运算符函数的方法

self_reference operator=( const SDAL_Const_Iter& src ) {
    index = src.index;
    return *this;
}
self_reference operator++() {
    index = index + 1;
    return *this;
}
self_type operator++(int) {
    SDAL_Const_Iter results = *this;
    ++index;
    return results;
}

index变量的类型为 const int

我的编译器抱怨我试图修改一个常量对象(更具体地说,"错误 C2166:l 值指定常量对象"),我知道这一点;但是,我没有看到其他方法来重载这些函数。有人可以详细说明如何在不引起编译器问题的情况下编写这些重载吗?

我相信

问题出在const int作为变量index

常量

迭代器不应允许对容器数据进行非常量访问。但是,迭代器本身是可变的(它必须能够迭代)。将index更改为int应该可以解决问题。