首页 > 解决方案 > C++ 有人可以解释一下这个 << 和 >> 操作重载以显示类内容吗?

问题描述

我希望这个问题不会被我禁止。

这是一个旋钮问题,但我不知道这里的情况如何。

我有以下istreamostream重载<<>>运算符。我用朋友功能做到了。

这是代码:

#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中的问题。

如果管理员想禁止我,那没关系,我应得的。

标签: c++operatorsoverloading

解决方案


推荐阅读