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?
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.