c++ - 如何返回一个类中的所有数据
问题描述
我是 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;
}
请让我知道如何回忆整个班级。
提前致谢 :)
解决方案
我看到你friend std::ostream& operator<<(std::ostream& s, Book const& b) { return s << b.title << b.author << b.pages;}
在课堂上添加了。这意味着您已经重载了<<
运算符。
您可以做的是std::cout<<book1;
不必像现在这样打印每个属性。
查看此站点以了解有关运算符重载的更多信息。
推荐阅读
- python - 如何在 python 上显示所有 8 位图像
- java - 打印多维数组行元素的替代方法
- python - Python,过滤csv以获取column1中的唯一值并返回
- javascript - RXJS:从 Promise 创建的级联 observables 的非顺序行为
- visual-studio - Postman JSON 不适用于 ASP.NET Core Web API
- cmake - cmake 使用通配符作为 find_library NAMES 选项
- python - Python:Discord.py 错误:无法为使用 PEP 517 且无法直接安装的 multidict、yarl 构建轮子
- r - dplyr:从子字符串的多个区域/字符变异
- list - 按下按钮时如何重置列表
- python - IndexError:带有 Google Cloud Vision API 的字节数组