繁体   English   中英

C ++运算符+重载

[英]C++ operator + overload

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

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;

如何实现该问题以适用于这两种情况。

如何实现该问题以适用于这两种情况。

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

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一起使用。

会员职能。

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.

首先, 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;
    */
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM