Ok, your operator+ doesn't return anything, and you are modifying the lhs operand, which is not necessary.
Your operator+ logic should be:
1. Create a new DArray object.
2. Resize the new DArray object's internal list array so it can fit all elements from both arrays (the this and the right-hand side operand).
3. Do a FOR loop that copies the elements in the first array into the new array.
4. Do a FOR loop that copes the elements in the second array into the new array.
5. Return the new array.
DArray<T> DArray<T>::operator+(const DArray& _d)
{
DArray<T> copy =*this;
DArray<T> _s;
delete[] list;
list = new T[size+1];
int nSize =0;
for(int i=0;i<size;i++) //here Ill get the new size needed for the new array
{if (_d.list[i]!=copy.list[i])
nSize++;
else
nSize++;
}
for(int i=0;i<nSize;i++) //after the previous step ill be copying the values of my original arrays in one array
{
if (_d.list[i]!=copy.list[i])
{
_s.list[i]=_d.list[i];
_s.list[i+1]=copy.list[i];
}
else
_s.list[i]=*_d.list;
return *this; //I believe this is how its supposed to be returned, the program run perfectly, but the output I require aint availble
}
}
Incorrect. Line 5 for instance deletes the inner list of the current object (the left-hand side operand of the binary + operator). This is NOT necessary. You must follow the logic I gave you exactly. No more, no less.
Also note that I told you to return the new array (step 5), not *this. *this is the "old" array, or one of the old arrays anyway.
My advise: Start the operator+ code from scratch. Delete everything inside it and start over following my logic exactly.
template<class T>
DArray<T> DArray<T>::operator-(const DArray &_d)
{
DArray<T> result = *this;
for(int i = 0; i < _d.length(); i++)
{
bool subtract = true;
for(int j = 0; j < size; j++)
{
/*I tried doing this in a couple of ways such that if list[i]==_d.list[i]
, then delete the ith element , but that wasnt possible;
else keep the element.
*/
}
}
return result;
}
Ok, yes, better. Note: It is considered bad practice to code if() statements like you did with the boolean variable "add". The result of operator== is of type boolean, so there really is no need to apply this operator over a boolean variable. In line 16, you should instead write if (add). If you were to ask if add were false, then it would be if (!add). The same is true for integers and pointers:
1 2 3 4 5 6 7 8 9 10
MyType *myPointer = NULL;
//Don't do this:
if (myPointer == NULL) ;
//Instead do this:
if (!myPointer) ;
int myVal = 0;
//Don't do this:
if (myVal != 0) ;
//Instead do this:
if (myVal) ;
As for your operator-(), you need to explain why you were unable to do what you wanted to do, exactly.
My advice is not to overload operator+ unless it preserves its original semantics. This usage seems to be less intuitive for users, so I would use a named function that would be more descriptive of the operation.