代码之家  ›  专栏  ›  技术社区  ›  Johnrad

C++链表栈操作符重载函数

  •  2
  • Johnrad  · 技术社区  · 15 年前

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

    //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>::Node::Node(std::basic_string,std::allocator>)'引用自C:\USERS\JOHNNY\DESKTOP\Stack\INFIX_TO_RPN.OBJ

    我的操作员过载功能可以解决这个问题吗?

    2 回复  |  直到 15 年前
        1
  •  2
  •   Michael Goldshteyn    15 年前

    在将数据推送到当前堆栈上之前,需要清空它。您应该添加一个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;
    }
    
        2
  •  1
  •   Community Mohan Dere    9 年前

    使用 the copy-and-swap idiom .

    一旦你实现了 swap() 函数(我在上面链接到的文章提供了有关如何执行此操作的出色描述) operator= 过载变得短暂而简单:

    Stack& operator=(Stack rhs)
    {
        swap(rhs);
        return *this;
    }