在将数据推送到当前堆栈上之前,需要清空它。您应该添加一个removeAll函数,并在赋值的顶部调用它(在检查self赋值之后,这也是一个好主意)。否则,它看起来是正确的。因此,最终结果将是:
//operator overload
template <class S>
const Stack<S>::operator=( const Stack& s )
{
// Check for self assignment
if (&s==this)
return *this;
// Clear the current stack
removeAll();
// Copy all data from stack s
if (!s.isEmpty())
{
NodePointer temp = q->theFront;
while(temp != 0)
{
push(temp->data);
temp = temp->next;
}
}
return *this;
}
下面是一个示例removeAll函数:
template <class S>
void Stack<S>::removeAll()
{
while (s.theFront)
{
NodePointer p = s.theFront;
s.theFront = s.theFront->next;
delete p;
}
s.theTop = s.theFront;
}