开发者

C++ OverLoading the << again

开发者 https://www.devze.com 2023-02-10 10:04 出处:网络
So my code is compiling ok - however it is not doing what i hoped :(. Ill try and explain this as best I can -

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 开发者_JAVA技巧<< 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)


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;        
}


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.


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;        
} 
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号