I have the following code with the overload output operator in it:
class Student
{
public:
string name;
int age;
Student():name("abc"), age(20){}
friend ostream& operator<<(ostream&, const Student&);
};
ostream& operator<<(ostream& os, const Student& s)
{
os << s.name; // Line 1
return os;
}
I was wondering what the difference if I changed Line 1 into this: cout << s.name?
Then the
operator <<would advertise that it can output the student’s name to any stream, but ignore its parameter and always output to standard out. As an analogy, it would be similar to writingYou can see that this is definitely a problem. If you really wanted to always return 4, then the function should have been
Of course you cannot make
operator <<take only one argument because it’s a binary operator so that’s where the analogy breaks down, but you get the picture.