Reputation: 51
So my code is compiling ok - however it is not doing what i hoped :(.
Ill try and explain this as best I can -
Below is my code that is writing to a file on disk.
void NewSelectionDlg::PrintInfoFile()
{
**CProductListBox b;**
ofstream outdata;
outdata.open("test.dat", ios::app); // opens the file & writes if not there. ios:app - appends to file
if( !outdata )
{ // file couldn't be opened
cerr << "Error: file could not be opened" << endl;
exit(1);
}
outdata << m_strCompany << endl;
outdata << m_strAppState << endl;
outdata << m_strPurpose << endl;
outdata << m_strChannel << endl;
outdata << m_strProductName << endl;
**outdata << b << endl;**
outdata << endl;
outdata.close();
return;
}
The key lines im concerned about are in Bold. I want to print out a class CProductListBox. Now as this is not a string, etc I know I have to over-ride the << in order to be able to do this. So my class for CProductListBox looks like this:
class CProductListBox : public CListBox
{
DECLARE_DYNAMIC(CProductListBox)
public:
CProductListBox();
virtual ~CProductListBox();
**friend std::ostream& operator<< (std::ostream& o, const CProductListBox& b)
{
return o;
}**
I have bolded again what i think is important - It is printing nothing on the output file unfortunately were I was hoping it would print the contenets of what is in b (the CProductList class).
Can anyone see something stupid I may be missing - Many Thanks,
Colly (Ireland)
Upvotes: 0
Views: 132
Reputation: 70909
For this to work, you need to supply some code in
friend std::ostream& operator<< (std::ostream& o, const CProductListBox& b)
{
return o;
}
Something like this would write b's "name" (assuming b has a getName() that returns a std::string) each time you wrote "b" to the ostream.
friend std::ostream& operator<< (std::ostream& o, const CProductListBox& b)
{
o << b.getName();
return o;
}
Upvotes: 0
Reputation: 91270
Your operator<< does not contain any code attempting to print anything.
friend std::ostream& operator<< (std::ostream& o, const CProductListBox& b)
{
o << b.SomeMember << b.AnotherMember;
return o;
}
Upvotes: 4
Reputation: 355069
Your operator<<
is getting called, but it doesn't do anything. It just returns the stream.
If you want it to write data to the stream, you need to write the code to write data to the stream.
Upvotes: 1