Book book;
list<Book>* books;

string title;
string author;
int ISBN;

     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 newBook;
}


在这里,我在Administration类中创建我的书本对象,问题是当我尝试从另一个类访问它们时,它说它们不存在。

我做了一些阅读,了解到我必须使用动态内存管理将对象分配到堆,有什么办法可以在我的代码中做到这一点?

任何帮助将不胜感激。

最佳答案

这是一个简单的方法:

if (userInput == "yes")
{
   Book *newBook = new Book(); // <-- allocates a Book object on the heap
   cout << "What is the title of the book you want to enter?" << endl;
   [...]
   newBook->setTitle(title);
   [...]
   return *newBook;
}

09-09 18:51