2011-02-15 77 views
0

所以我的代码编译正常 - 但它不是做什么,我希望:(C++超载<<再次

生病尝试,并解释这是尽我所能 -

下面是我的代码,被写入到磁盘上的文件。

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

关键线即时关注以粗体显示。我想打印出来的一类CProductListBox。现在因为这不是一个字符串,等我知道我必须高估乘坐< <为了能够做到这一点。所以我的班级CProductList盒看起来是这样的:

class CProductListBox : public CListBox 
{ 
    DECLARE_DYNAMIC(CProductListBox) 

public: 
    CProductListBox(); 
    virtual ~CProductListBox(); 
    **friend std::ostream& operator<< (std::ostream& o, const CProductListBox& b) 
     { 
     return o;   
    }** 

我又是什么,我认为加粗是很重要的 - 这是印刷没事就输出文件不幸被我希望它会打印什么是B中的contenets(在CProductList类) 。

有人能看到一些愚蠢的事我可能会丢失 - 非常感谢,

Colly(爱尔兰)

+7

你`运营商<<`没有做任何事情;如果你想将数据写入流,你需要编写的代码将数据写入到流... – 2011-02-15 16:48:29

回答

1

operator<<获取调用,但它不会做任何事情。它只是返回流。

如果你想让它写入数据流,你需要编写的代码将数据写入到流。

4

您的运营< <不含试图打印任何东西,任何代码。

friend std::ostream& operator<< (std::ostream& o, const CProductListBox& b) 
{ 
    o << b.SomeMember << b.AnotherMember; 
    return o;   
} 
+0

感谢埃里克 - 我想这也是工作,如果我有三个下拉列表的方式(我们会打电话给他们1,2,3) - 基于这些数据显示在另一个框中(这是CProductListBox) - 可以说,如果选择了1,2,3,则ABC将显示。如果选择2,1,3 BAC将显示等等。所以我想要做的是返回此CProductListBox类的完整内容 - 是否可以做o << b;然后返回o?由于 – user617702 2011-02-16 14:13:36

0

对于这个工作,你需要在

friend std::ostream& operator<< (std::ostream& o, const CProductListBox& b) 
{ 
    return o;   
} 

像这样的东西提供一些代码,会写B的“名”(假设1b具有的getName()返回一个的std :: string )每次你写入“b”到ostream。

friend std::ostream& operator<< (std::ostream& o, const CProductListBox& b) 
{ 
    o << b.getName(); 
    return o;   
} 
+0

感谢埃德温 - 我想这也是工作的方式是,如果我有三个下拉列表(我们会打电话给他们1,2,3) - 基于这些数据显示在另一个盒子(这是CProductListBox) - 让说如果选择了1,2,3,则会显示ABC。如果选择2,1,3 BAC将显示等等。所以我想要做的是返回此CProductListBox类的完整内容 - 是否可以做o << b;然后返回o?谢谢 – user617702 2011-02-16 14:13:07