list<Book> *books = new list<Book>;
list<Book>::iterator pos;
void Administrator::addBook()
{
Book *newBook = new Book();
cout << "Would you like to enter a book?" << endl;
cin >> userInput;
cout << endl;
if (userInput == "yes")
{
cout << "What is the title of the book you want to enter?" << endl;
cin >> title;
cout << "What is the author of the book you want to enter?" << endl;
cin >> author;
cout << "What is the ISBN of the book you want to enter?" << endl;
cin >> ISBN;
cout << endl;
newBook->setTitle(title);
newBook->setAuthor(author);
newBook->setISBN(ISBN);
newBook->setAvailability(true);
books->push_back(*newBook);
}
}
*****************
我真的需要帮助,我今天收到了一些答案,但没有人帮我解决这个问题。这是我的admin
课程。它在堆上创建书籍并将其存储在stl::list
void Guest::searchBook(Book* search)
{
string searchBook;
cout << "What book would you like to search for?" << endl;
cin >> searchBook;
printBookDetails();
}
这是我的Guest
课程,我想在这里做的是搜索我在Administrator
课程中创建的书籍列表,但是当它进入函数printBookDetails
时,我的清单中没有任何元素,我假设它们已被销毁。
Administrator* admin1 = new Administrator("jayfitz91", 24681357);
Guest* guest1 = new Guest("guest", 0000);
void main()
{
//Everything here works fine
admin1->addBook();
admin1->addBook();
admin1->makeAvailable();
admin1->printBookDetails();
//My list is destroyed at this point and it returns nothing
guest1->printBookDetails();
我的Guest
班级继承了printBookDetails
班级的Administrator
所有管理功能都可以工作,但一旦到达访客,元素就会消失。
无论如何我能解决这个问题吗?非常感谢帮助
答案 0 :(得分:0)
感谢@OldProgrammer,我意识到我必须从我的Admin
类返回书籍列表,并将其作为参数传递给我的访客类中的printBookDetails
方法:
//Admin class
//Now returning a list
list<Book> Administrator::addBook()
{
Book *newBook = new Book();
cout << "Would you like to enter a book?" << endl;
cin >> userInput;
cout << endl;
if (userInput == "yes")
{
cout << "What is the title of the book you want to enter?" << endl;
cin >> title;
cout << "What is the author of the book you want to enter?" << endl;
cin >> author;
cout << "What is the ISBN of the book you want to enter?" << endl;
cin >> ISBN;
cout << endl;
newBook->setTitle(title);
newBook->setAuthor(author);
newBook->setISBN(ISBN);
newBook->setAvailability(true);
books->push_back(*newBook);
}
return *books;
}
//Guest class function
void Guest::printBookList(list<Book> *tempList)
{
pos = tempList->begin();
for (pos = tempList->begin(); pos != tempList->end(); ++pos)
{
cout << pos->getTitle() << "\n"
<< pos->getAuthor() << "\n"
<< pos->getISBN() << "\n"
<< pos->getAvailability() << "\n"
<< "******************************" << endl;
}
}
//Main class function
//Create a temporary variable for the list
list<Book> tempList;
//pass it through to the method
guest1->printBookList(&tempList);
答案 1 :(得分:-1)
首先,您不必动态创建列表对象。
list<Book> books = new list<Book>();
你这样做是因为
您的责任较少:您不必释放图书所包含的资源。它会自动释放。
list是一个stl容器,这意味着它会自动处理动态分配。
如果使用动态分配的数组,则会有所不同......
我认为您的列表“已消失”是因为访客和管理员有两个完全不同的列表。
要解决此问题,您应该授予管理员对您的访客拥有的图书清单的访问权限。
或者提取图书清单并将其存储在另一个允许访问管理员和访客列表的类中。