【问题标题】:std::ostream & operator << using a function within my classstd::ostream & operator << 在我的班级中使用一个函数
【发布时间】:2017-03-02 04:44:14
【问题描述】:

所以我有一个需要将对象打印到 ostream 的 ostream 运算符。简单的权利。我有一个打印功能,它需要一个 ostream 并且也做同样的事情。我的 ostream 被定义为我班上的朋友。我只想知道如何在我的操作员中使用我的打印功能......我的打印功能也使用枚举

void Box::print(std::ostream & out, Box::Type type) const
{
switch (type)
{
case FILLED:
    for (int i = 0; i < _height; i++)
    {
        for (int j = 0; j < _width; j++)
        {
            out << "x";
        }
        out << std::endl;
    }
    break;
case HOLLOW:
    for (int i = 0; i < _height; i++)
    {
        for (int j = 0; j < _width; j++)
        {
            if (i == 0 || i == _height - 1 || j == 0 || j == _width - 1)
                out << "x";
            else
                out << " ";
        }
        out << std::endl;
    }
    break;
case CHECKERED:
    for (int i = 0; i < _height; i++)
    {
        for (int j = 0; j < _width; j++)
        {
            if ((i % 2 == 0 && j % 2 == 0) || (i % 2 != 0 && j % 2 != 0))
            {
                out << "x";
            }
            else
            {
                out << " ";
            }
        }
        out << std::endl;
    }
    break;
}
}



std::ostream & operator<<(std::ostream &out, Box &b1)
{
   return b1.print(out, Box::Type type) // obviously dosent exist here
}

【问题讨论】:

  • 您可能想要使用switch,而不是if 语句链。还有为什么(Type type == HOLLOW)
  • 从重载运算符调用函数与从其他任何地方调用函数没有什么不同。
  • return b1.print(out, FILLED);(或 HOLLOW 或在这种情况下要调用的任何类型)
  • 啊,是的,谢谢你,我真是个白痴,我也可能会做一个 switch 语句而不是这些 if 语句。类型也是枚举
  • @SamuelGrenon 你还没有真正回答完他的问题。 if (Type type == HOLLOW) 应该做什么? IE。你想在那里做什么?

标签: c++ enums operator-keyword ostream


【解决方案1】:

两种选择:

第一个是将Type 添加为类的成员,您可以从运算符中访问它。

第二个是实际上用 std::pair 重载 ostream 运算符。 例如:

ostream& operator<<(ostream& os, const std::pair<Box, Type>& p) {
    p.first.print(os, p.second);
    return os;
} 

【讨论】:

  • 别忘了return os;
猜你喜欢
  • 2022-08-04
  • 1970-01-01
  • 2013-07-28
  • 2023-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-11
相关资源
最近更新 更多