gpt4 book ai didi

c++ - 队列 C++ 的运算符重载

转载 作者:太空宇宙 更新时间:2023-11-04 16:27:59 25 4
gpt4 key购买 nike

我试图使用重载运算符方法将一个队列的条目复制到另一个队列,但我的函数出错了。我不知道还有什么方法可以通过以下方式访问“原始”队列的值:

struct Node
{
int item;
Node* next;
};

class Queue
{
public:
// Extra code here
void operator = (const Queue &original);
protected:
Node *front, *end;
};

void Queue::operator=(const Queue &original)
{
//THIS IS WHERE IM GOING WRONG
while(original.front->next != NULL) {
front->item = original.front->item;
front->next = new Node;
front = front->next;
original.front = original.front->next;
}
}

最佳答案

你有函数式拷贝构造函数吗?如果是这样,我将根据您的复制构造函数实现您的赋值运算符,如下所示:

#include <algorithm>  // <utility> for C++11

void Queue::operator=(const Queue &other)
{
// Assumes your only field is the "front" pointer.

Queue tmp(other); // May throw.
std::swap(front, tmp.front); // Will not throw.
}

这个想法是你在一个临时对象中执行任何可能抛出异常的操作(比如你对 operator new() 的调用),该临时对象将清理资源,然后“提交” "通过在非抛出操作中交换内容来进行更改,这样即使在构造 tmp 期间抛出异常,您的 Queue 的状态也是正常的。指针赋值保证不会抛出,这就是为什么在这种情况下对 std::swap() 的调用不会抛出。离开赋值运算符的范围后,tmp 的析构函数应该清理旧的链接列表,因为它的 front 已与旧的 front 交换。

参见 GotW #59有关此“copy-to-temporary-and-swap”习语的详细信息,以及它与强异常安全保证的关系。

关于c++ - 队列 C++ 的运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10081130/

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