C++ 运算符 + 重载

标签 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;

我怎样才能解决这两种情况的问题。

最佳答案

How can I implement the problem to work for both the cases.

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

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

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

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

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

改进建议。

  1. 将非常量 operator+= 成员函数添加到 DynamicVector
  2. 允许 operator+ 函数与 const 对象一起使用。

成员函数。

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.

关于C++ 运算符 + 重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49543637/

相关文章:

arrays - 在 Angular 的 Select Option 中获取选中的对象

Ruby 使用 max_by 在多维数组中查找具有最大值的元素

arrays - 对 m 维上的 n 维数组求和的最紧凑方法

windows - 发布Qt项目时如何设置Qt dll的相对路径?

c# - 使用用户选择的维度创建数组

c++ - SetWindowsHookex 在一段时间后停止工作

c++ - 在一个窗口中显示多个 MRI 切片

c++ - 设置特定于音频端点设备的应用程序(以编程方式)

c++ - 如何使用 CGAL 简化组合映射

c - 使用动态字符串从 C 中的字符串中删除一个字符