在 C++ 中重载 IO 运算符时使用 cout/cin?
我正在测试一些与重载 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
区别很明显,is/os 是输入/输出流,而 cin/cout 是标准输入/输出流。 cin/cout 是 I/O 流的实例,而不是同义词。
重点是,除了标准输入/输出之外,还有其他流,例如文件、字符串流以及您能想到的任何自定义实现。如果您在流操作符中使用 cin/cout,忽略它们应该读/写的流,那么您最终将
打印到标准输出,而不是打印到应该打印的文件。
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
printing to the standard output, rather than to the file where its supposed to.