I've attempted to overload the "+" operator for template. Yet I get a debug error abort() has been called
. The "+" operator should add an item to the end of the list, then return the result.
So if I'm right, let's assume list1
has integer items of {4,2,1}. I am guessing writing myList<int> list2 = list1 + 5
should make list2 contain the items {4,2,1,5}
template <class type>
class myList
{
protected:
int length; //the number of elements in the list
type *items; //dynamic array to store the elements
public:
myList();
//adds one element to a list
friend myList& operator+ (myList<type> &lhs, const type& t)
{
myList<type> result;
if (lhs.items == NULL)
{
result.items = new type[1];
result.items[0] = t;
result.length++;
}
else
{
type *temp = new type[lhs.length];
for (int i = 0; i < lhs.length; i++)
{
temp[i] = lhs.items[i];
}
result.items = new type[lhs.length + 1];
for (int i = 0; i < lhs.length; i++)
{
result.items[i] = temp[i];
}
result.items[lhs.length] = t;
result.length++;
}
return result;
}
}
template <class type>
myList<type>::myList()
{
length = 0;
items = new type;
items = NULL;
}
So what should be done in this case?
EDIT: I fixed it. I had to remove & from the return type. Is there any other possible way to fix it? or must & be removed?