【发布时间】: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