Im trying to add to objects of class Vector1 Vector1 has:
int dim; // the dimension
int *x; // the values of all dimensions.
when constructed the user can set the dim and all the values.
Now i try to do this in main:
cout << (vector1 + vector2)[i]; // print x[i] of the sum.
to do this I overloaded both + and [] operators, but Im not sure of how to do + correctly
///////////// At first I thought I would do:
Vector1 &Vector1::operator+(const Vector1 &v2) {
if (dim == v2.dim)
{
for (int i=0 ; i<dim ; i++)
x[i] = x[i] + v2.x[i];
}
else {
cout << "Error! Vectors from different dimensions";
exir(1);
}
return *this;
}
but then I realized that Im overwriting Vector1 this way, I want to be able to get the solution without overwriting any data so I thought of this:
Vector1 &Vector1::operator+(const Vector1 &v2) {
Vector1 temp;
if (dim == v2.dim)
{
temp.dim = dim;
int *arr = new int[dim];
for (int i=0 ; i<dim ; i++)
arr[i] = x[i] + v2.x[i];
}
else
{
cout << "Error! Vectors from different dimensions";
exit(1);
}
return temp;
}
now im not sure if the "temp" vector I'm returning will be deleted after the "cout << ..." line or that it will stay in memory even though Im not using it anymore...
Can someone explain to me how to do this correctly?
Thnx