我试图为模板重载“+”运算符。但是我收到了调试错误abort() has been called
。 “+”运算符应将项添加到列表的末尾,然后返回结果。
所以,如果我是对的,我们假设list1
的整数项为{4,2,1}。我猜写myList<int> list2 = list1 + 5
应该使list2包含项目{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;
}
那么在这种情况下应该做些什么呢?
编辑:我修好了。我不得不删除&amp;从返回类型。有没有其他可能的方法来解决它?或必须&amp;被删除?