0

我创建了一个名为 e 的链表。我使用复制构造函数来创建 e2,但由于某种原因,当我尝试打印 e2 时程序总是崩溃。有人可以向我解释并帮我解决这个问题,谢谢。

#include <iostream>
#include <ctime>
#include <cmath>

using namespace std;

class Element
{

public: Element();//constructor
    Element(const Element&); //copy constructor

    //Element& Element::operator =(const Element & from);
     void Addelement(int row, int col, int value);
     void swap(int num,int x, int arr[100]);
     void printelement();
     void rowordermajor();

private:


    typedef Element* ElementPtr;


        int row;
        int col;
        int value;
        ElementPtr next; 


    ElementPtr head;

    bool comparegreater(ElementPtr temp1, ElementPtr temp2);

};

int main()
{
Element e;
for (int i=0;i<5;i++)
{
    e.Addelement(i,i,i);



}
e.printelement();

Element e2(e);
//e2.printelement();

system("PAUSE");

}



Element::Element()//normal constructor
{
head=NULL;
}

Element::Element(const Element& e)
{
   this->row=e.row;
   this->col=e.col;
   this->value=e.value;
   this->next=e.next;


}

void Element::Addelement(int row, int col, int value )
{

ElementPtr temp= new Element;
temp->row=row;
temp->col=col;
temp->value=value;
temp->next=head;
head=temp;
 }



         void Element::printelement()//why does it print backwards
{
ElementPtr temp=head;

while (temp != NULL)
{
    cout<<"( "
        <<temp->row
        <<" , "
        <<temp->col
        <<" , "
        <<temp->value
        <<" ) ";

    cout<<endl;

    temp=temp->next;
}

}
4

1 回答 1

2

因为当您使用带有as 参数的构造函数时,您没有分配NULL(或可能)到 head 。this->head = e.head;Element& e

于 2013-02-09T11:11:59.310 回答