2

operator<<サイズが不明な配列の内容を出力するためにオーバーロードするのに問題があります。私は解決策を探しましたが、私が見つけた唯一の方法は、すべてのプライベート データ メンバーを構造体に入れる必要があるというものでした (これは私には少し不必要に思えます)。関数を編集してフレンドにしたり、 (または const)に変更*qしたりすることはできません。&q

これが私の << オーバーロード コードです。

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

どんな助けでも大歓迎です。ありがとうございました!

4

2 に答える 2

4

もう 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;
}
于 2011-10-29T04:22:57.690 に答える
1

一般的に、operator<<テイクをconst Quack&ではなく にする必要がありQuack*ます。

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

これをQuackクラス定義に入れます:

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

これによりoperator<<、 のプライベート メンバーにアクセスできるようになりますq

于 2011-10-29T03:59:36.583 に答える