C++ 重载 << 错误

标签 c++ operator-overloading ostream

我希望得到一些帮助来解决我遇到的错误 - 我已经搜索过类似的问题,但这些问题并没有真正给我我想要的东西。下面列出了代码片段:

class NewSelectionDlg : public CDialog
{
// Construction
public:

  class CProductListBox
  {
    public:
    friend ostream& operator <<(ostream& o, const CProductListBox& b);
  };
   ostream& operator<<(ostream& o,  const CProductListBox& b)
  {
        std::cout << o.m_lstEclispeProducts;
        return o;
  }

我有一个包含多个字符串的列表框 - 这些字符串可能因所选的其他下拉框而异。我想将此框中的内容添加到文件中,以及用户从填充它的下拉列表中选择的内容。但是我收到以下错误(我在 VS 2008 中开发)。

error C2804: binary 'operator <<' has too many parameters
error C2333: 'NewSelectionDlg::operator <<' : error in function declaration; skipping function body

我不确定为什么,因为我相信重载运算符的语法是可以的 - 任何人都可以看到我做的愚蠢或可能错过的任何事情 - 非常感谢任何帮助。

最佳答案

声明友元时,只需在类定义之外定义它或在子类中定义它:

class NewSelectionDlg : public CDialog
{
// Construction
public:

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

// (...) Rest of NewSelectionDlg
}; 

ostream& operator <<(ostream& o, const NewSelectionDlg::CProductListBox& b)
{
    // Did you meant:
    return o << b.m_lstEclispeProducts;
} 

class NewSelectionDlg : public CDialog
{
// Construction
public:

  class CProductListBox
  {
    public:
    friend ostream& operator <<(ostream& o, const CProductListBox& b)
    {
        // Did you meant:
        return o << b.m_lstEclispeProducts;
    }
  };

// (...) Rest of NewSelectionDlg
}; 

关于C++ 重载 << 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5003424/

相关文章:

c++ - 当我有两个对象时如何重载运算符<<??(有关系)

c++ - 在 C++ 中到达 .eof() 后如何返回到文件的开头?

C++ 大数运算

c++ - operator= in c++(11)工作方向

javascript - Javascript 中数组的重载 [] 运算符

c++ - 重载 operator<<(ostream&, T) 其中 T 是 "enum class MyEnum"

c++ - std::ostream::operator<< 没有为 std::string 定义?

c++ - CMake - 尝试构建项目时遇到 undefined reference

c++ - 具有方法概括 make_shared 和 make_unique 的复合指针特征类?

C++ 多态打印