我有一个动态数组,我需要创建一个重载运算符 + 的函数,这样它应该可以让您以两种方式向数组添加新的对象元素:
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;
}
改进建议。
- 将非常量
operator+=
成员函数添加到DynamicVector
。 - 允许
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/