队列C++的运算符重载

Operator Overloading for Queue C++

本文关键字:重载 运算符 C++ 队列      更新时间:2023-10-16

我试图使用重载运算符方法将一个队列的条目复制到另一个队列中,但我的函数出错了。我不知道除了下面我所拥有的之外,还有什么其他方式可以访问队列"原始"的值:

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。

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