我目前正在开发一个实现链表的堆栈。在重载“=”运算符时遇到问题。我对于该做什么一点也很无能为力。如果有人能指出我的方向很棒,那将是非常棒的。
//operator overload
template <class S>
const Stack<S>::operator=( const Stack& s )
{
if (s.isEmpty())
theFront = theTop = 0
else
{
NodePointer temp = q->theFront;
while(temp != 0)
{
push(temp->data);
temp = temp->next;
}
}
return *this;
}
我也遇到了这个错误: Stack,std :: allocator&gt; &gt; :: Node :: Node(std :: basic_string,std :: allocator&gt;)'从C:\ USERS \ JOHNNY \ DESKTOP \ STACK \ INFIX_TO_RPN.OBJ引用
这可以通过我的运算符重载函数来修复吗?
答案 0 :(得分:2)
在推送数据之前,您需要清空当前堆栈。你应该添加一个removeAll函数,并在赋值的顶部调用它(在检查自我赋值之后,这也是一个好主意)。否则,看起来是正确的。所以,最终结果将是:
//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;
}
答案 1 :(得分:1)
不要手动为您的班级实施复制赋值运算符,而是使用the copy-and-swap idiom。
一旦为您的课程实现了swap()
功能(我上面链接的文章提供了如何执行此操作的绝佳说明),operator=
重载变得简短而简单:< / p>
Stack& operator=(Stack rhs)
{
swap(rhs);
return *this;
}