我正在上课,现在我想制作Car对象的链表。所以为此,我有一个Node类来保存每个节点的数据。
class StringOfCar;
class Node
{
private:
Node* next;
Car* data;
Node ()
{
next = 0;
data = 0;
}
public:
friend class StringOfCar;
};
和StringOfCar
class StringOfCar
{
private:
Node* head;
Node* tail;
public:
StringOfCar(){
head=0;
tail=0;
}
void output();
void push (Car &);
};
现在我使用此功能毫无问题地推送元素:
void StringOfCar::push(Car & new_car)
{
Car *currentCarPtr;
Node *currentNodePtr;
currentNodePtr = new Node;
currentCarPtr = new Car(new_car);
currentNodePtr->next = 0;
currentNodePtr->data = &new_car;
if (head == 0)
{
head = currentNodePtr;
tail = currentNodePtr;
}
else
{
tail->next = currentNodePtr;
tail = currentNodePtr;
}
}
但是当我尝试输出时,程序突然停止。我也有Car类的输出()。这两个类的输出函数如下:
void StringOfCar::output(){
Node * currentNodePtr = head;
if (head == 0)
cout << "NO cars \n";
else
{
while (currentNodePtr != 0)
{
currentNodePtr->data->output();
currentNodePtr = (currentNodePtr->next);
}
}
}
对于Car class:
void Car::output()
{
cout<<"\nreportingMark "<<setw(3)<<reportingMark;
cout<<"\ncarNumber "<< setw(8)<< carNumber;
cout<<"\nkind " << setw(13)<<KIND_ARRAY[kind];
if (loaded==true)
{
cout<<" \nloaded true";
}
else if (loaded == false)
{
cout<< "\nloaded false";
}
cout<< "\ndestination "<<setw(7)<<destination<<endl;
}
当我评论currentNodePtr-&gt; data-&gt; output();这一行,它工作正常。有什么问题?请帮忙
答案 0 :(得分:0)
我认为问题出在这一行:
currentNodePtr->data = &new_car;
函数void StringOfCar::push(Car & new_car)
的。
那应该是
currentNodePtr->data = currentCarPtr;