簡體   English   中英

在堆棧類C ++的框架中復制構造函數和/或pop方法

[英]Copy Constructor and/or pop method in framework for a stack class C++

因此,我有一個由隨機生成的字符串組成的堆棧,然后有一個指向.cpp代碼中下一項的指針。 然后,我將每個項目從堆棧中彈出並打印出來。 但是最后我遇到了段錯誤,所以我猜我正在嘗試從堆棧中彈出一個我不擁有內存的項目。

我相信我的復制構造函數是不正確的-也許它沒有在我的堆棧中將最后一個值設置為null,但是我無法弄清楚為什么在放置該行時它沒有將值設置為NULL

newPrev-> next = NULL;

這是我的代碼(僅適用於班級)

    #include <string>
    using namespace std;
    class Stack 
    {
    protected:
        struct Node 
        {
            string item;
            Node* next; 
        }; // struct Node

    public:
        // constructor of an empty stack
        Stack ()
        {
            head = NULL;
        }

        // copy constructor
        Stack( const Stack & rhs )
        {
            if (rhs.head == NULL) {// check whether original is empty
                head = NULL; 
            }else{
                head = new Node;
                head->item = rhs.head->item;
                Node* newPrev = head;
                // Now, loop through the rest of the stack
                for(Node* cur = rhs.head->next; cur != NULL; cur = cur->next)
                {   
                    newPrev->next = new Node;
                    newPrev = newPrev->next;
                    newPrev->item = cur->item;
                } // end for 

                newPrev->next = NULL;

            } // end else
        }

        // destructor
        ~Stack ()
        {
            delete head; 
        }

        // assignment
        const Stack & operator=( const Stack & rhs )
        {
            return *this;
        }

        // query whether the stack is empty
        bool empty () const
        {
            return false;
        }

        // add an item to the top of the stack
        // this method is complete and correct
        void push (const string & new_item)
        {
            Node* new_node = new Node;
            new_node->item = new_item;
            new_node->next = head;
            head = new_node;
        }

        // remove the item on the top of the stack
        void pop ()
        {
            if (head!=NULL){
                Node *n = head;
                head = head->next;
                delete n;
            } 
        }

        // return the item on the top of the stack, without modifying the stack
        string & top () const
        {
            return head->item;
        }

    private:
        Node* head;
    };

您的復制構造函數很好。 您沒有實現bool Stack::empty()函數。 我將其更改為:

// query whether the stack is empty
bool empty () const
{
    return head == NULL;
}

運行得很好:

int main()
{
    Stack s;
    s.push("a");
    s.push("b");
    Stack b(s);
    while(!s.empty())
    {
        cout << s.top() << endl;
        s.pop();
    }
    while(!b.empty())
    {
        cout << b.top() << endl;
        b.pop();
    }
    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM