C ++运算符+重载

时间:2018-03-28 20:30:29

标签: c++ arrays dynamic overloading operator-keyword

我有一个动态数组,我需要创建一个重载运算符+的函数,这样它就可以让你以两种方式向数组中添加一个新的对象元素:

array=array+element; and array=element+array;

到目前为止,我有这个功能:

DynamicVector& DynamicVector::operator+(const TElement& e)
{
if (this->size == this->capacity)
     this->resize();
this->elems[this->size] = e;
this->size++;
return *this;
}

但这只适用于第一种情况,当我们执行array=array+element;

如何解决这两种情况的问题。

2 个答案:

答案 0 :(得分:2)

  

如何解决这两种情况的问题。

您需要将该函数重载为非成员函数。

DynamicVector& operator+(const TElement& e, DynamicVector& v);

理想情况下,将它们都作为非成员函数。

您可以使用第一个实现第二个。

DynamicVector& operator+(const TElement& e, DynamicVector& v)
{
   return v + e;
}

改善建议。

  1. 将非const operator+=成员函数添加到DynamicVector
  2. 允许operator+个函数与const objets一起使用。
  3. 会员功能。

    DynamicVector& DynamicVector::operator+=(const TElement& e)
    {
       if (this->size == this->capacity)
         this->resize();
       this->elems[this->size] = e;
       this->size++;
       return *this;
    }
    

    非会员职能。

    DynamicVector operator+(DynamicVector const& v,  TElement const& e)
    {
       DynamicVector copy(v);
       return (copy += e);
    }
    
    DynamicVector operator+(TElement const& e, DynamicVector const& v)
    {
       return v + e;
    }
    

    通过这些更改,重载的运算符就像基本类型一样。

    int i = 0;
    i += 3; // Modifies i
    int j = i + 10;  // Does not modify i. It creates a temporary.
    

答案 1 :(得分:1)

首先,operator+不应该修改要添加的左手对象。它应该返回一个新对象,它是添加在一起的两个输入的副本,例如:

DynamicVector DynamicVector::operator+(const TElement& e) const
{
    DynamicVector tmp(*this);
    if (tmp.size == tmp.capacity)
      tmp.resize();
    tmp.elems[tmp.size] = e;
    tmp.size++;

    /* NOTE: the above can be optimized to avoid unnecessary reallocations:

    DynamicVector tmp;
    tmp.capacity = size + 1; // or rounded up to some delta...
    tmp.size = size + 1;
    tmp.elems = new TElement[tmp.capacity];
    std::copy(elems, elems + size, tmp.elems);
    tmp.elems[size] = e;
    */

    return tmp;
}

您正在考虑使用operator+=,它应该修改要添加的对象,并返回对它的引用:

DynamicVector& DynamicVector::operator+=(const TElement& e)
{
    if (size == capacity)
        resize();
    elems[size] = e;
    size++;
    return *this;
}

现在,为了回答你的问题,你需要定义operator+的单独的非成员重载来处理TElement位于左侧的情况,例如:

DynamicVector operator+(const TElement& e, const DynamicVector &v)
{
    return v + e;
}

或者:

DynamicVector operator+(const TElement& e, const DynamicVector &v)
{
    DynamicVector tmp(v);
    tmp += e;
    return tmp;

    /* alternatively:

    return DynamicVector(v) += e;
    */

    /* NOTE: the above can be optimized to avoid unnecessary reallocations:

    DynamicVector tmp;
    tmp.capacity = v.size + 1; // or rounded up to some delta...
    tmp.size = v.size + 1;
    tmp.elems = new TElement[tmp.capacity];
    std::copy(v.elems, v.elems + v.size, tmp.elems);
    tmp.elems[v.size] = e;
    return tmp;
    */
}