c++ - C++ 有人可以解释一下这个 << 和 >> 操作重载以显示类内容吗?
问题描述
我希望这个问题不会被我禁止。
这是一个旋钮问题,但我不知道这里的情况如何。
我有以下istream和ostream重载<<和>>运算符。我用朋友功能做到了。
这是代码:
#include <iostream>
#include <string>
class Employee {
std::string name;
int age;
public:
Employee(std::string p_name = "", int p_age = 0)
{
name = p_name;
age = p_age;
}
friend std::istream& operator >> (std::istream& s, Employee& e);
friend std::ostream& operator << (std::ostream& s, Employee& e);
};
std::istream& operator >> (std::istream& s, Employee& e)
{
std::cout << "\nEnter name: "; s >> e.name;
std::cout << "\nEnter age: "; s >> e.age;
return s;
}
std::ostream& operator << (std::ostream& s, Employee& e)
{
s << "Name: " << e.name << std::endl;
s << "Age:" << e.age << std::endl;
return s;
}
int main()
{
const int MAX = 1024;
Employee emp1("Lucas", 40), emp2("Disch", 35);
std::cout << "Employee 1 is: \n" << emp1 << '\n'
<< "Employee 2 is: \n" << emp2 << std::endl;
return 0;
}
如果我们重载了 >> 和 << 运算符,并且重载的运算符就像 function() 为什么在 main() 函数中的行:
std::cout << "Employee 1 is: \n" << emp1 << '\n'
<< "Employee 2 is: \n" << emp2 << std::endl;
仅接收 Employee 类并自动传递/接收 ostream 和 istream,执行 << 或 >>?
请我搜索谷歌我没有得到答案。
正如任何人都可以看到我有点迷失在 C++ 中的 I/O 和搜索和谷歌并没有说清楚。甚至是stackoverflow中的问题。
如果管理员想禁止我,那没关系,我应得的。
解决方案
推荐阅读
- jenkins - 除了第三个星期四之外,如何每天在 Jenkins 管道中安排工作
- php - 如何将字符串转换为 JSON 格式
- python - 这个 unboundLocal 错误在这个 python 代码中指的是什么?
- c - 制作一个简单的登录功能。如何在 for 循环中实现 Sizeof?什么是结构?
- reactjs - 使用 redux 访问嵌套的 prop
- python - Python设置可选变量
- r - 解决在r中使用“row_to_names”后获取因子变量而不是整数的问题
- flutter - DART:从另一个文件导入时如何从 Future 类中获取列表?
- google-chrome-extension - chrome.identity.launchWebAuthFlow 适用于 Windows,但不适用于 Chrome 操作系统
- python-3.x - 输入没有提示输入数据。我该如何解决?