gpt4 book ai didi

c++ - 在堆栈类 C++ 的框架中复制构造函数和/或 pop 方法

转载 作者:行者123 更新时间:2023-11-28 07:25:51 24 4
gpt4 key购买 nike

所以我有一个由随机生成的字符串组成的堆栈,然后是指向我的 .cpp 代码中下一项的指针。然后我检查并从堆栈中弹出每个项目并将它们打印出来。不过我在最后遇到了一个段错误,所以我猜我正试图将一个项目弹出到我不拥有内存的堆栈中。

我相信我的复制构造函数是不正确的 - 也许它没有将我堆栈中的最后一个值设置为 null 但我无法弄清楚为什么当我放置该行时它没有将值设置为 NULL

newPrev->next = NULL;

这是我的代码(仅限类(class))

    #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;
}

关于c++ - 在堆栈类 C++ 的框架中复制构造函数和/或 pop 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18753608/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com