通过重载运算符+添加2个指针,导致无限循环c ++



我正在编写我的 Arrayhandler 类,我需要重载 operator+operator++

通过

operator+(1)超载operator++是个好主意吗?我得到一个无限循环,因为据我所知_current = _pointee + ii size_t的位置)不会改变_current.为什么?以这种方式添加指针是否正确?

class ArrayHandler
{
private:
     size_t _size;
     Pointee *_pointee; 
     Pointee *_end;
     mutable Pointee *_current; 
  ....
}

我的Ctor:

template <typename Pointee>
    ArrayHandler<Pointee>::ArrayHandler(size_t size):
        _size(size), _pointee(new Pointee[_size]), _end(_pointee+_size), _current(_pointee)
        {};

操作员+ :

ArrayHandler<Pointee>& ArrayHandler<Pointee>::operator+(size_t i)
    {
        if (!defined())
            throw MisUse(undefArray, 0);
        if ( _pointee + i > _end || _pointee + i < _pointee)
            throw MisUse(badIndex, i);
        _current = _pointee + i;
        return *this;
    };

运算符++:

template <typename Pointee>
ArrayHandler<Pointee>& ArrayHandler<Pointee>::operator++()
{
    if (!defined())
        throw MisUse(undefArray, 0);
    if ( stop() )
        throw MisUse(badIndex, 0);
    ++_current;*/
    this->operator+(1);
    return *this;
};

导致无限执行的 while 循环:

while (!ar3.stop())
    {
        ++ar3;
        ++count;
    }

stop()方法:

 bool stop() const {return _current ==_end;} 

更新:

无限 while 循环的原因是我通过运算符 + 实现了运算符++,就我而言,每次都更改了 start+1 _current,因此在第二次迭代后,我的_current保持不变。 每次都由 start+1 反复重置。

人!!

你犯了一个错误 wrt 运算符重载: 你的operator+修改了它的参数!考虑:

int a = 1;
int b = 2;
int c = a + b;

您是否希望a在您调用a + b时被修改?当然不是。

您要做的是正确实现operator+=,然后提供一个operator+和(如果需要)一个内部使用您的operator+=operator++(可能是前缀++i和后缀i ++版本)。以下是后者的一些草图,它们超出了作为自由函数的类定义:

template <typename Pointee>
ArrayHandler<Pointee> operator+( ArrayHandler<Pointee> arg, size_t i )
{
    arg += i;
    return arg;
}
template <typename Pointee>
ArrayHandler<Pointee>& operator++( ArrayHandler<Pointee>& arg ) // prefix ++
{
    arg += 1;
    return arg;
}
template <typename Pointee>
ArrayHandler<Pointee> operator++( ArrayHandler<Pointee> arg, int ) // postfix ++
{
    arg += 1;
    return arg;
}

现在对于operator+=,你可以像这样实现它(作为成员函数):

ArrayHandler<Pointee>& ArrayHandler<Pointee>::operator+=(size_t i)
{
    if (!defined())
        throw MisUse(undefArray, 0);
    if ( _current + i >= _end || _current + i < _pointee)
        throw MisUse(badIndex, i); // this message is now probably misleading
    _current += i;
    return *this;
};

这通过i元素推进_current,这是operator+=的预期语义。如果您只想访问 i -th 元素,则应考虑编写 operator[]

您还可以考虑将帮助程序库用于样板代码,例如 Boost.Operator,请参阅我的个人资料以获取一些链接。

在您的运算符 + 中,您不会增加电流,而是每次将其重置为 start+i;

_current = _pointee + i;

您可能打算这样做:

_current = _current + i;

最新更新