C++ - 链表堆栈运算符重载函数

标签 c++ operator-overloading stack linked-list

我目前正在开发一个实现链表的堆栈。我在重载“=”运算符时遇到问题。我非常不知道该怎么办。如果有人能给我指出一个好的方向,那就太好了。

//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/

相关文章:

c++ - 数组运算符 [] 重载 const 和非常量版本

c++ - 继承std::ostream 和QString 的operator<< 的类

c - 打印出堆栈给出了奇怪的定位

c++ - C++11 : is there a simple way to seed the generator in one place of the code, 中的随机数然后在不同的函数中使用它?

c++ - pthread 看不到作为参数传递的实例变量

c++ - 嵌套调用中的数组运算符 (->) 重载

algorithm - 不使用图形可能有任何有效的解决方案吗?

Javascript - 使用箭头函数重写 for 循环?

c++ - "ListNode dummy{-1, head};"是什么意思?

c++ - 自动收报机中断会干扰硬件中断吗?