c++ - 在 C++ 中重载 IO 运算符时使用 cout/cin?

标签 c++ io operators overloading

我正在测试一些与重载 IO 运算符相关的 C++ 代码。代码如下:

class Student {
 private:
     int no;
 public:
     Student(int n)
     {
         this->no = n;
     }
     int getNo() const {
         return this->no;
     }
     friend istream& operator>>(istream& is, Student& s);
     friend ostream& operator<<(ostream& os, const Student& s);
 };
 ostream& operator<<(ostream& os, const Student& s){
     cout << s.getNo(); // use cout instead of os
     return os;
}
istream& operator>>(istream& is, Student& s) 
{
    cin >> s.no; // use cin instead of is
    return is;
}

但是,在 << 内和>> ,我可以使用:

 ostream& operator<<(ostream& os, const Student& s){
     os << s.getNo(); // use os instead of cout
     return os;
}
istream& operator>>(istream& is, Student& s) 
{
    is >> s.no; // use is instead of cin
    return is;
}

<< ,我使用 os 对象而不是 cout 以及 >> 的相似性运算符(operator)。所以,我很好奇这是否有什么区别?

最佳答案

区别很明显,is/os是输入/输出流,而cin/cout是标准输入/输出流。 cin/cout 是 I/O 流的实例,而不是同义词。

重点是,除了标准输入/输出之外,还有其他流,例如文件、字符串流以及您能想到的任何自定义实现。如果您在流操作符中使用 cin/cout,忽略它们应该读/写的流,那么您最终会得到

file_stream << some_student;

打印到标准输出,而不是打印到应该打印到的文件。

关于c++ - 在 C++ 中重载 IO 运算符时使用 cout/cin?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7383103/

相关文章:

c# - C# 中的 'or' 运算符是指 "and/or"还是 "one or the other"?

c++ - 代码适用于示例运行但提交失败 : Hackerrank problem

C++:如何获取文件夹列表

c++ - 将 Doxygen 注释与 cppcheck-suppress 混合

websocket - Socket.IO 连接上的无限循环

java - java.io.File 中允许的文件分隔符

C++,从文件中读取一个数字数组

excel - 两个减号在一起的含义 ("double unary")

c++ - OpenCV + VideoInput.lib 高清摄像头

java - 字符串和整数的评估顺序