Click to See Complete Forum and Search --> : How to overload operator<<


Bernd Huber
January 21st, 2002, 06:48 AM
I wrote that class below with three members. I will stream the object 'MyStr' to
'Cout' by overloading the operator&lt;&lt;. Hopefully somebody can help me why this
source code couldn't work.

//class to stream
class CMyStream
{
private:
long m_lValue;
string m_str;
double m_dValue;
public:
CMyStream(long lValue=0, string str="", double dValue=0.0):m_lValue(lValue), m_str(str), m_dValue(dValue){};
virtual ~CMyStream() {};

long numberLong()const {return m_lValue;};
string numberString()const {return m_str;};
double numberDouble()const {return m_dValue;};

friend ostream& operator&lt;&lt;(ostream& of, const CMyStream& MyStr);
};

//Global declaration of operator&lt;&lt;
ostream& operator&lt;&lt;(ostream& of, const CMyStream& MyStr)
{
of &lt;&lt; MyStr.numberLong &lt;&lt; '/' &lt;&lt; MyStr.numberString &lt;&lt; '/' &lt;&lt; MyStr.numberDouble;
return of;
}


//main for streamin an object
int main(int argc, char* argv[])
{
long lValue = 91287364;
CMyStream MyStr(123564, "TestText", 56.78);

cout &lt;&lt; lValue;//this one works
cout &lt;&lt; MyStr;//this won't

return 0;
}

Igor Soukhov
January 21st, 2002, 08:46 AM
The problem was hidden in the overloaded operator:


//Global declaration of operator&lt;&lt;
ostream& operator&lt;&lt;(ostream& of, const CMyStream& MyStr)
{
//was of &lt;&lt; MyStr.numberLong &lt;&lt; '/' &lt;&lt; MyStr.numberString &lt;&lt; '/' &lt;&lt; MyStr.numberDouble;
of &lt;&lt; MyStr.numberLong() &lt;&lt; '/' &lt;&lt; MyStr.numberString() &lt;&lt; '/' &lt;&lt; MyStr.numberDouble();
return of;
}




It's quite simple that MyStr.numberLong evaluates as the address of member function ... that why you got bogus output.

Please - rate answer if it helped you
It gives me inspiration when I see myself in the top list =)

Best regards,

-----------
Igor Soukhov (Brainbench/Tekmetrics ID:50759)
igor@soukhov.com | ICQ:57404554 | http://soukhov.com

Russian Software Developer Network http://rsdn.ru

NMTop40
January 21st, 2002, 09:37 AM
1. MyStr.numberLong, MyStr.numberString and MyStr.numberDouble are all functions. Therefore you need to put brackets in.

2. Unless you have defined it yourself, ostream &lt;&lt; std::string is not defined (it didn't used to be, maybe it is now). Anyway if you put c_str() if that fails. Thus

of &lt;&lt; MyStr.numberString().c_str()




3. As all the functions of CMyStream you are calling from the operator&lt;&lt; overload function are public, there is no need to declare that function as a friend.



The best things come to those who rate

NMTop40
January 21st, 2002, 09:48 AM
by the way on point (2) you can do

ostream &lt;&lt; std::string



as long as you include &lt;string&gt; as well as &lt;xstring&gt; (in Visual C++ 6.0 anyway)



The best things come to those who rate