|
-
January 21st, 2002, 07:48 AM
#1
How to overload operator<<
I wrote that class below with three members. I will stream the object 'MyStr' to
'Cout' by overloading the operator<<. 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<<(ostream& of, const CMyStream& MyStr);
};
//Global declaration of operator<<
ostream& operator<<(ostream& of, const CMyStream& MyStr)
{
of << MyStr.numberLong << '/' << MyStr.numberString << '/' << 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 << lValue;//this one works
cout << MyStr;//this won't
return 0;
}
-
January 21st, 2002, 09:46 AM
#2
Re: How to overload operator<<
The problem was hidden in the overloaded operator:
//Global declaration of operator<<
ostream& operator<<(ostream& of, const CMyStream& MyStr)
{
//was of << MyStr.numberLong << '/' << MyStr.numberString << '/' << MyStr.numberDouble;
of << MyStr.numberLong() << '/' << MyStr.numberString() << '/' << 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)
[email protected] | ICQ:57404554 | http://soukhov.com
Russian Software Developer Network http://rsdn.ru
-
January 21st, 2002, 10:37 AM
#3
Re: How to overload operator<<
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 << 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 << MyStr.numberString().c_str()
3. As all the functions of CMyStream you are calling from the operator<< overload function are public, there is no need to declare that function as a friend.
The best things come to those who rate
-
January 21st, 2002, 10:48 AM
#4
Re: How to overload operator<<
by the way on point (2) you can do
ostream << std::string
as long as you include <string> as well as <xstring> (in Visual C++ 6.0 anyway)
The best things come to those who rate
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|