首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++ OverLoading <<再一次

C++ OverLoading <<再一次
EN

Stack Overflow用户
提问于 2011-02-16 00:46:03
回答 3查看 109关注 0票数 0

所以我的代码编译得很好--但是它没有做我希望的事情:(.

我会尽我所能解释这一点-

下面是我在磁盘上写文件的代码。

代码语言:javascript
复制
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。现在,由于这不是一个字符串等,我知道我必须覆盖<<才能做到这一点。所以我的CProductListBox类看起来像这样:

代码语言:javascript
复制
class CProductListBox : public CListBox
{
    DECLARE_DYNAMIC(CProductListBox)

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

我再次强调了我认为重要的内容-它没有在输出文件上打印任何内容,不幸的是,我希望它会打印b中的内容( CProductList类)。

有没有人看到我可能漏掉的愚蠢的东西-非常感谢,

Colly (爱尔兰)

EN

回答 3

Stack Overflow用户

发布于 2011-02-16 00:49:46

您的operator<<不包含任何试图打印任何内容的代码。

代码语言:javascript
复制
friend std::ostream& operator<< (std::ostream& o, const CProductListBox& b) 
{
  o << b.SomeMember << b.AnotherMember;
  return o;        
}
票数 4
EN

Stack Overflow用户

发布于 2011-02-16 00:49:32

您的operator<<正在被调用,但它没有做任何事情。它只是返回流。

如果希望它将数据写入流,则需要编写代码将数据写入流。

票数 1
EN

Stack Overflow用户

发布于 2011-02-16 00:51:37

要实现这一点,您需要在

代码语言:javascript
复制
friend std::ostream& operator<< (std::ostream& o, const CProductListBox& b) 
{
    return o;        
} 

这样的代码会在您每次向ostream写入"b“时写入b的"name”(假设b有一个返回std::string的getName() )。

代码语言:javascript
复制
friend std::ostream& operator<< (std::ostream& o, const CProductListBox& b) 
{
    o << b.getName();
    return o;        
} 
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5006618

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档