Suppose I have the following class:
class Example
{
int m_a;
int m_b;
public:
// usual stuff, omitted for brevity
friend ostream & operator<< (ostream & os, const Example &e)
{
return os << m_a << m_b;
}
};
I want to keep default behavior for cin
, but the following format when writing to ofstream
:
m_a , m_b
I have tried searching here, but haven't found any similar question.
I have tried searching online, but still haven't found anything helpful.
I have tried to add
friend ofstream & operator<< (ofstream & ofs, const Example &e)
{
return ofs << m_a << ',' << m_b;
}
into the class, but that produced a compiler error. To be honest, this approach feels wrong, but i had to try it before coming here for help.
When chaining operators, all the standard <<
will return an ostream&
reference.
Then your return ...
will not work, because the value doesn't match the ofstream&
return type.
Just use ostream&
in your user defined operator<<
, and it should work.