【问题标题】:How do I overload the ostream operator<< with an array?如何用数组重载 ostream 运算符<<?
【发布时间】:2011-12-17 17:23:33
【问题描述】:

我在重载operator&lt;&lt; 以打印未知大小数组的内容时遇到问题。我搜索了一个解决方案,但我找到的唯一一个需要我将所有私有数据成员放在一个结构中(这对我来说似乎有点不必要)。我无法编辑该函数以使其成为朋友或将 *q 更改为 &amp;q(或 const)。

这是我的

ostream& operator<<(ostream& out, Quack *q)
{
    if (q->itemCount() == 0)
        out << endl << "quack: empty" << endl << endl;
    else
    {
        int i;
        int foo;
        for (int i = 0; i < q->itemCount(); i++ )
        {
            foo = (*q)[i];
            out << *(q + i);
        } // end for
        out << endl;
    }

    return out;
}

这是我的私人数据成员:

private:
int     *items;                     // pointer to storage for the circular array.
                                    // Each item in the array is an int.
int     count;
int     maxSize;
int     front;
int     back;

这是函数的调用方式(无法编辑):

    quack = new Quack(QUACK_SIZE);
    //put a few items into the stack
    cout << quack;

以下是输出的格式:

quack: 1, 2, 3, 8, 6, 7, 0

如果数组为空,则

quack: empty

任何帮助将不胜感激。谢谢!

【问题讨论】:

  • 所以,你在尝试做鸭式打字,嗯?
  • 如果operator &lt;&lt;不被允许成为朋友,为什么还要列出Quack的私有字段呢? Quack 的哪些公共方法允许访问单个项目或 Quack::items 以及项目计数?
  • @snazzy:如果你不能修改Quack,那么你需要在你的问题中说出来。
  • 谢谢。我编辑了我的帖子以添加调用功能。我还记得 Quack 公共类中有一个 itemCount 函数。
  • 有什么问题?您的函数看起来没问题,除了 (a) 您使用 q 作为 Quack 而不是 Quack*,以及 (b) 函数不应该 使用 Quack*

标签: c++ arrays overloading operator-keyword ostream


【解决方案1】:

另一种选择是重定向到成员函数,如下所示:

void Quack::printOn(ostream &out) const
{
    out << "quack: ";
    if(count == 0)
        out << "empty";
    else 
    {
        out << items[0];
        for ( int i = 1 ; i < count ; i++ )
        {
            out << ",  " << items[i];
        }
    }
    out << "\n";
}

ostream &operator<<(ostream &out,const Quack &q)
{
    q.printOn(out);
    return out;
}

【讨论】:

    【解决方案2】:

    通常你应该让你的operator&lt;&lt; 使用const Quack&amp;,而不是Quack*

    ostream& operator<<(ostream& out, const Quack &q)
    {
       ...
    }
    

    把它放在你的 Quack 类定义中:

    friend ostream &operator<<(ostream &stream, const Quack &q);
    

    这将允许您的 operator&lt;&lt; 访问 q 的私有成员。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-10
      • 1970-01-01
      • 2010-10-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多