`你好 我刚刚在代码块中写了这段代码,在编译和运行后,它说程序已停止工作。我找不到我做错了什么。我不知道问题是否与我的代码有关,或者是与我正在使用的编译器或其他内容有关的问题。 请帮助.exe已停止工作代码块cpp
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);
}
缩进代码然后使用调试器....您会发现错误在哪里。 – jpo38
'Library :: book * Library :: initNode(string s,int i)'应该可能是一个'book'构造函数。 “图书馆”不应该知道如何构建一本书。这是'书'的工作。 – user4581301
'void displayList(book * ptr)const'必须将一本书传递给'displayList'似乎有点奇怪。 'displayList'已经知道它的列表。当前的实现将允许用户调用'a.displayList(b.head);'来获取'b'列表,这只是愚蠢的。另一方面,'static void displayList(book * ptr)'是有意义的。 – user4581301