我目前正在开发一个实现链表的堆栈。我在重载“=”运算符时遇到问题。我非常不知道该怎么办。如果有人能给我指出一个好的方向,那就太好了。
//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;
}
我也收到此错误: 堆栈,std::allocator >>::Node::Node(std::basic_string, std::allocator >)' 从 C:\USERS\JOHNNY\DESKTOP\STACK\INFIX_TO_RPN.OBJ 引用
这可以通过我的运算符重载函数来解决吗?
最佳答案
在向当前堆栈推送数据之前,您需要清空当前堆栈。您应该添加一个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;
}
关于C++ - 链表堆栈运算符重载函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4065996/