我的Copy Constructor有什么问题?

时间:2012-02-24 23:06:31

标签: c++ class constructor copy

当我到达复制构造函数时为什么会崩溃?

在我的类定义中找到的复制过程中,我确保在复制开始之前将作为其他原始队列的副本创建的队列为空:让我们说队列q1不为空并且我想把q1变成q2。我想在将q2的内容复制到q1 ..

之前清空q1的内容
#include <iostream>
#include <string>
#include <cassert>

using namespace std;

class Dnode
{
    public:
       Dnode(int);
       int  n;
       Dnode*   l, *r;
};

Dnode::Dnode(int tx)
{
    n = tx;
    l = r = NULL;
}

class Queue // reminder: insertions at the rear, deletions at the front
{
    public:
       Queue();
       void enqueue(int x);
       int dequeue(void);
       bool empty(void) const;
       void display(void) const;
       Queue(const Queue&); //copy constructor

    private:
       Dnode*   front, *back;
       void copy(Dnode*);
       void free();

};

Queue::Queue()
{
    front = back = NULL;
}


void Queue::enqueue(int x)
{
    Dnode*  d = new Dnode(x);
    if (empty())
        front = back = d;
    else
    {
        back->r = d;
        d->l = back;
        back = d;
    }
}

int Queue::dequeue(void)
{
    assert(! empty());
    Dnode*  temp = front;
    front = front->r;
    if (front == NULL)
        back = NULL;
    else    front->l = NULL;
    int x = temp->n;
    delete temp;
    return x;
}


bool Queue::empty(void) const
{
    return front == NULL;
}

void Queue::display(void) const
{
    for (Dnode* d = front; d != NULL; d = d->r)
        cout << d->n << " ";
    cout << endl;
}

void Queue::copy(Dnode* dn) // "dn" will be "Front" of Queue being copied
{                           // this procedure will be called in Copy Constructor  
    Dnode* temp=front;      // found underneath this procedure
    while(front!=back)      
    {                       
        front=front->r;
        delete temp;
        temp=front;
    }

    delete temp;

    front=back=temp=NULL;

    if(dn!=NULL)
    {
        while(dn->r!=NULL)
        {
            enqueue(dn->n);
            dn=dn->r;
        }
        enqueue(dn->n);
    }
}

Queue::Queue(const Queue& x)
{
    copy(x.front);
}

int main()
{
    Queue   q;
    if (q.empty()) cout << "q empty" << endl;

    for (int i = 0; i < 10; i++) q.enqueue(i);

    q.display();

    int x = q.dequeue();

    cout << "x is " << x << endl;

    q.display();

    Queue q1(q); //<----program crashes when we get here

    q1.display();
}

3 个答案:

答案 0 :(得分:3)

您将复制构造函数与赋值运算符混淆。在赋值运算符中,您必须删除当前队列并将其替换为第二个参数的副本。但这是一个复制构造函数。没有当前队列。您的会员未初始化。因此,当您开始尝试删除现有队列时,您就会弄乱未初始化的指针。

答案 1 :(得分:2)

您忘记在复制构造函数中初始化backfront

void Queue::copy(Dnode* dn) // "dn" will be "Front" of Queue being copied
{   
  Dnode* temp=front;      // found underneath this procedure
  while(front!=back)      
  {                       
      front=front->r;
      delete temp;
      temp=front;
  }

然后while循环随机行动,因为front被酉化,导致崩溃。

答案 2 :(得分:0)

您需要将前后指针初始化为null,然后遍历源Queue x获取每个Dnode并将其排入新队列。