`你好 我刚刚在代码块中编写了这段代码,在构建和运行之后,它说程序已停止工作。我无法找到我做错了什么。我不知道问题是否与我的代码有关,或者与我正在使用的编译器有什么关系。 请帮忙
Library.h:
#ifndef LIBRARY_H
#define LIBRARY_H
#include <iostream>
#include <string>
using namespace std;
class Library
{
public:
struct book
{
string tittle;
int number;
struct book* next;
}* head, *tail, *ptr;
Library();
~Library();
book* searchName(book *, string);
void addNode(book *);
book *initNode(string s, int i);
void displayNode(book *ptr) const;
void displayList(book *ptr) const;
protected:
};
#endif
Library.cpp
#include "Library.h"
Library::Library() :
head(NULL), tail(NULL)
{
}
Library::~Library()
{
book *current, *temp;
current = head;
temp = head;
while (current != NULL)
{
current = current->next;
delete temp;
temp = current;
}
}
Library::book * Library::searchName(Library::book* ptr, string name)
{
while (name != ptr->tittle)
{
ptr = ptr->next;
if (ptr == NULL)
break;
}
return ptr;
}
void Library::addNode(book *newNode)
{
if (head == NULL)
{
head = newNode;
head = newNode;
}
tail->next = newNode;
newNode->next = NULL;
tail = newNode;
}
Library::book *Library::initNode(string s, int i)
{
book *ptr = new book;
if (ptr == NULL)
return static_cast<book *>(NULL);
else
{
ptr->tittle = s;
ptr->number = i;
return ptr;
}
}
void Library::displayNode(book *ptr) const
{
cout << ptr->number << ": " << ptr->tittle << endl;
}
void Library::displayList(book *ptr) const
{
if (!ptr)
cout << "Nothing to display" << endl;
while (ptr)
{
displayNode(ptr);
ptr = ptr->next;
}
}
main.cpp
#include "Library.h"
#include <iostream>
using namespace std;
int main()
{
Library a;
Library::book *ptrr;
ptrr = a.initNode("s1", 1);
a.addNode(ptrr);
ptrr = a.initNode("s2", 2);
a.addNode(ptrr);
a.displayList(a.head);
}
答案 0 :(得分:0)
当您从a.addNode(ptrr)
拨打第一个main
时,它会tail->next = newNode;
(Library::addNode
内),但tail
为NULL
(它没有分配),它崩溃....
现在,代码中可能还有其他问题,但这很可能是第一个让程序停止工作的问题......
请注意,代码中的某些内容可以简化。
像:
Library::book *Library::initNode(string s, int i)
{
book *ptr = new book;
if (ptr == NULL)
return static_cast<book *>(NULL);
else
{
ptr->tittle = s;
ptr->number = i;
return ptr;
}
}
可能只是:
Library::book *Library::initNode(string s, int i)
{
book *ptr = new book;
if (ptr != NULL)
{
ptr->tittle = s;
ptr->number = i;
}
return ptr;
}
和
void Library::addNode(book *newNode)
{
if (head == NULL)
{
head = newNode;
head = newNode;
}
tail->next = newNode;
newNode->next = NULL;
tail = newNode;
}
应该是:
void Library::addNode(book *newNode)
{
if ( newNode != NULL ) // just in case
{
if (head == NULL)
{
head = newNode; // one is enough
}
if ( tail != NULL ) // to fix your crash
tail->next = newNode;
newNode->next = NULL;
tail = newNode;
}
}
另外,请参阅user4581301注释,析构函数代码甚至不编译....