gpt4 book ai didi

c++ - 队列段错误的复制构造函数

转载 作者:行者123 更新时间:2023-11-27 23:03:23 25 4
gpt4 key购买 nike

我需要为队列类做复制构造函数。这是我的代码。我不知道为什么我会遇到段错误!

Queue::Queue()
{
front = NULL;
rear = NULL;
numItems = 0 ;
}

// Copy constructor
Queue::Queue(const Queue& queueToCopy)
{
//QueueNode *newNode;//pointer to a new node
QueueNode *nodePtr;//traverse pointer

newNode = new QueueNode;
nodePtr = queueToCopy.front;
while (nodePtr != NULL){
enqueue(nodeNode->value);
nodePtr = nodePtr->next;
}
}

///////////////////////////这是我测试复制构造函数时的主要功能

int main()
{
Queue obj;
//enqueue....
...
// Testing Queue copy constructor
Queue objQ2(objQ);
cout << "The values in the queue objQ2 were: \n";
while (!objQ2.isEmpty()){
int value;
objQ2.dequeue(value);
cout << value << endl;
}
}

最佳答案

我不确定你想用 newNode 做什么,但你的循环条件似乎是错误的,因为 newNode 似乎在循环中从未改变过。正如@RSaha 的评论,可能不需要 newNode,所以:

while (nodePtr != NULL){
enqueue(nodePtr->value);
nodePtr = nodePtr->next;
}

关于c++ - 队列段错误的复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25541604/

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