当我重载 operator+ 时发生了一些奇怪的事情
我有一个单链表,我重载了 operator+ 和 operator=
这是我对两者的实现(编辑:使用 insertFront 和复制构造函数):
AnyList::AnyList(const AnyList& list)
{
count = list.getCount();
first = list.getFirst();
AnyList a;
a.setFirst(first);
a.setCount(count);
Node *current = first;
for (int i = 0; i < count; ++i)
{
a.insertFront(current->getData());
current = current ->getLink();
}
}
-
void AnyList::insertFront(int value)
{
Node *newNode = new Node;
newNode -> setData(value);
newNode -> setLink(first);
first = newNode;
++count;
}
AnyList AnyList::operator+ (const AnyList& list) const
{
Node *current = first;
Node *listCurrent = list.getFirst();
int sumHolder = 0;
AnyList temp;
while(current != NULL)
{
sumHolder = current ->getData() + listCurrent ->getData();
temp.insertFront(sumHolder);
current = current ->getLink();
listCurrent = listCurrent ->getLink();
}
return temp;
}
AnyList& AnyList::operator=(const AnyList& rightSide)
{
if(&rightSide != this)
{
Node *travel = rightSide.getFirst();
first = rightSide.getFirst();
Node *original = first;
while (travel != NULL)
{
original ->setData(travel ->getData());
original ->setLink(travel ->getLink());
travel = travel->getLink();
original = original ->getLink();
}
}
return *this;
}
以下是主要内容:
AnyList mylist;
AnyList mylist2;
for (int i = 0; i < 10; ++i)
{
mylist.insertFront(i);
}
for (int i = 10; i < 20; ++i)
{
mylist2.insertFront(i);
}
mylist.print();
cout << endl << endl;
mylist2.print();
cout << endl;
AnyList sumList = mylist + mylist2;
sumList.print();
cout << endl;
我的输出如下(这是我想要的输出):
9 8 7 6 5 4 3 2 1 0
19 18 17 16 15 14 13 12 11 10
10 12 14 16 18 20 22 24 26 28
所以,我的问题是,当我改为写:
AnyList sumList;
sumList = mylist + mylist2;
sumList.print();
当它进入打印函数并尝试从函数 getData() 返回数据时出现错误访问错误
我超级不知道为什么会这样,任何帮助将不胜感激!
谢谢!