【问题标题】:Printing out elements in a list打印出列表中的元素
【发布时间】:2013-11-22 23:24:46
【问题描述】:
Book Administrator::bookDetails()
{
    Book book;
    list<Book> books;

    string title;
    string author;
    int ISBN;

    string userInput;

    while (userInput != "q")
    {
        cout << "Would you like to enter a book?" << endl;
        cin >> userInput;
        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;

            book.setTitle(title);
            book.setAuthor(author);
            book.setISBN(ISBN);

            books.push_back(book);

        }

        list<Book>::iterator pos;
        pos = books.begin();

        for (pos = books.begin(); pos != books.end(); pos++)
        {
                    //There error is produced here
            cout << *pos << "\n";
        }

    }
    return book;
}

这是我的管理类的bookDetails 函数。它循环并询问书名、作者和 ISBN 号,完成后将书推送到列表中。

当我调试它时这似乎工作正常,但是当我尝试使用迭代器打印出每本书的详细信息时出现错误。

有人可以帮我吗? 谢谢

【问题讨论】:

  • 你在调试器中输入了什么,调试器说了什么?
  • 我得到一个错误 - 什么是错误?

标签: c++ list loops


【解决方案1】:

你需要为Book实现operator&lt;&lt;

std::ostream operator<<(std::ostream& os, const Book& book)
{
   os << book.title << " " << book.author; // print out other information
   return os;
}

【讨论】:

  • 这解决了它,非常感谢。我会尽快选择你的答案(再过 8 分钟)
  • @user2757842 很高兴它有帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-11
  • 1970-01-01
  • 1970-01-01
  • 2018-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多