C++ 队列C+的运算符重载+;

C++ 队列C+的运算符重载+;,c++,class,queue,operator-overloading,C++,Class,Queue,Operator Overloading,我试图使用重载运算符方法将一个队列的条目复制到另一个队列中,但我的函数出错了。我不知道如何以任何其他方式访问队列“original”的值,除了下面的方法: struct Node { int item; Node* next; }; class Queue { public: // Extra code here void operator = (const Queue &original); protected: Node *front, *end

我试图使用重载运算符方法将一个队列的条目复制到另一个队列中,但我的函数出错了。我不知道如何以任何其他方式访问队列“original”的值,除了下面的方法:

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.
}

#包括有关“复制到临时和交换”习惯用法的详细信息,以及它与强异常安全保证的关系。

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

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

#详细介绍“复制到临时并交换”的习惯用法,以及它与强异常安全保证的关系。

已经有了一个
std::queue
类。已经有了一个
std::queue
类。这不是我正在做的吗?不。你总是在修改版本的前端。在上面的版本中,是在开始之前修改的,但不是在循环中,因此前端不会改变,并指向队列的开始。唷,我认为想法很简单-修改的内容不同。在您的示例中,您正在更改引用中的对象,在我的示例中,您有自己的变量,您可以更改注意这是意外的,目标队列是扩展的,而不是赋值的(哪个运算符=意味着)。这不是我正在做的吗?不。您总是在您的版本中修改前端。在上面的版本中,是在开始之前修改的,但不是在循环中,因此前端不会改变,并指向队列的开始。唷,我认为想法很简单-修改的内容不同。在您的示例中,您正在更改引用中的对象,在我的示例中,您有自己的变量,您可以更改注意这是意外的,目标队列是扩展的,而不是赋值的(运算符=意味着)。