首页 > 解决方案 > 如何返回一个类中的所有数据

问题描述

我是 C++ 新手(以及一般的编码)并且喜欢学习它。我目前正在学习课程,我想找到一种方法来一次性打印整个课程,而不是回忆个别部分。我在 stackReview 上发布,我收到了对我的代码的回复:friend std::ostream& operator<<(std::ostream& s, Book const& b) { return s << b.title << b.author << b.pages;}。我不完全确定我是如何打印这个的。请在下面查看我的代码:

#include <iostream>

class Book{

    public:
        std::string title;
        std::string author;
        int pages;
        friend std::ostream& operator<<(std::ostream& s, Book const& b) { return s << b.title << b.author << b.pages;}
    Book(std::string aTitle, std::string aAuthor, int aPages){
        title = aTitle;
        author = aAuthor;
        pages = aPages;
                }
};


int main(){
    Book book1("Harry Potter", "JK Rowling", 500);
    Book book2("Lord of the Rings", "Tolkein", 750);
    Book book3("Hunger Games", "Author for Book", 250);
    std::cout<<book1.title;
    std::cout<<book2.author;
    std::cout<<book3.pages;

//Currently I'm  calling from the class by doing the above. But it'd be great to learn how
//to recall a whole class in one go, rather than doing `std::cout<<book1.title;`.

return 0;
}

请让我知道如何回忆整个班级。

提前致谢 :)

标签: c++class

解决方案


我看到你friend std::ostream& operator<<(std::ostream& s, Book const& b) { return s << b.title << b.author << b.pages;}在课堂上添加了。这意味着您已经重载了<<运算符。

您可以做的是std::cout<<book1;不必像现在这样打印每个属性。

查看此站点以了解有关运算符重载的更多信息。


推荐阅读