【问题标题】:Use cout/cin when overloading IO Operators in C++?在 C++ 中重载 IO 运算符时使用 cout/cin?
【发布时间】:2011-09-12 03:45:28
【问题描述】:

我正在测试一些与重载 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;
}

但是,在&lt;&lt; 和&gt;&gt; 中,我可以使用:

 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;
}

在&lt;&lt; 中,我使用os 对象而不是cout 和&gt;&gt; 运算符的相似性。所以,我很想知道这有什么不同吗?

【问题讨论】:

    标签: c++ io operators overloading


    【解决方案1】:

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

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

    file_stream << some_student;
    

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

    【讨论】:

    • 标准输入/输出流是什么意思?它们是“在计算机程序开始执行时在计算机程序与其环境(通常是文本终端)之间预先连接的输入和输出通道”(en.wikipedia.org/wiki/Standard_streams)吗??
    猜你喜欢
    • 1970-01-01
    • 2018-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多