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

发布于 2024-12-03 23:24:19 字数 1143 浏览 5 评论 0原文

我正在测试一些与重载 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 以及 >> 运算符的相似性。所以,我很好奇这是否有什么区别?

I am testing some C++ code related to overloading IO operators. The code as follows:

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

However, inside the << and >>, I can use:

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

In <<, I use os object instead of cout and the similarity for >> operator. So, I am curious to know if there is any difference of that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

和影子一齐双人舞 2024-12-10 23:24:19

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

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

file_stream << some_student;

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

The difference is obvious, is/os are input/output streams while cin/cout are the standard input/output streams. cin/cout are instances of i/o streams, not synonyms.

The point being, there are streams other than standard input/output, such as files, string streams, and whatever custom implementation you can think of. If you use cin/cout in your streaming operators, ignoring the stream they should read/write to, then you'll end up with

file_stream << some_student;

printing to the standard output, rather than to the file where its supposed to.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文