I need to implement the overloading of the += operator in c++. I have a Vector class and my implentation of += needs to add an integer from the back of my Vector.
For example: if my vector V1 contains of {1, 2, 3} and I write V1 += 4, it needs to give me {1, 2, 3, 4}.
I have almost the same functionality with the overload of the + operator which receives a Vector and an int and adds the given integer to the back of the array.
Fields for my class
class Vector
{
unsigned int _size;
int * _list;
HERE IS MY NON-WORKING SOLUTION FOR += OPERATOR
Vector& operator+=(const int val)
{
Vector temp;
temp._list = new int[_size + 1];
temp._size = this->_size + 1;
for (unsigned int i = 0; i < temp._size; i++)
{
if (i < temp._size - 1)
{
temp._list[i] = this->_list[i];
}
else if (i == temp._size - 1)
{
temp._list[i] = val;
}
}
return temp;
}
AND ALMOST IDENTICAL WORKING SOLUTION FOR + OPERATOR
friend Vector operator+(Vector lhs, const int val)
{
Vector temp;
temp._list = new int[lhs._size + 1];
temp._size = lhs._size + 1;
for (unsigned int i = 0; i < temp._size; i++)
{
if (i < temp._size - 1)
{
temp._list[i] = lhs._list[i];
}
else if (i == temp._size - 1)
{
temp._list[i] = val;
}
}
return temp;
}
I can't understand where is the key difference, however I am guessing it is somewhere in & or friend concepts, cuz I dont'really understand how they are working in this case.
And one more thing I MUST NOT CHANGE THE DESCRIPTION OF MY METHODS. (just the implementation)