1

このトピックに関する他のスレッドを見たことがありますが、特に役に立ちませんでした。.html ファイルに出力するクラスを作成しています。ostream をフレンドとして宣言しましたが、まだクラスのプライベート メンバーにアクセスできません。

私の.hファイル

    #ifndef OUTPUTTOHTML_H
    #define OUTPUTTOHTML_H
    #include <iostream>
    #include <string>
    #include <vector>
    using std::string;
    using std::vector;
    using std::ostream;

    namespace wilsonOutput
    {
    class HTMLTable
    {
      private:
        vector<string> headers;
        vector<vector<string> > rows;
        //helper method for writing an HTML row in a table
        void writeRow(ostream &out, string tag, vector<string> row);

        public:
        // Set headers for the table columns
        void setHeaders(const vector<string> &headers);
        // Add rows to the table
        void addRow(const vector<string> &row);
        //write the table innto HTML form onto an output stream
        friend ostream & operator<<(ostream & out, HTMLTable htmlTable); 
    };
    }

    #endif

これは、オーバーロードを実装するために main.cpp (メイン コード ブロックではなく) にあるものです。

    // Overloaded stram output operator <<
    ostream & operator<<(ostream &out, wilsonOutput::HTMLTable htmlTable)
    {
        out << "<table border = \"1\">\n";
        // Write the headers
        htmlTable.writeRow(out, "th", htmlTable.headers);
        // Write the rows of the table
        for (unsigned int r = 0; r < htmlTable.rows.size(); r++)
        {
            htmlTable.writeRow(out, "td", htmlTable.rows[r]);
        }
        // Write end tag for table
        out << "</table>\n";
        return out;
    }

どんな助けでもかなり... 役に立ちます。

4

1 に答える 1

3

クラス内のfriend宣言は、演算子を周囲の名前空間(wilsonOutput)に配置します。おそらく、実装はその名前空間にありません。その場合、それはあなたがそれを入れた名前空間にある演算子の別個のオーバーロードを宣言し、そのオーバーロードはクラスの友達ではありません。

実装するときに名前空間を指定する必要があります。

ostream & wilsonOutput::operator<<(ostream &out, wilsonOutput::HTMLTable htmlTable)
{      // ^^^^^^^^^^^^^^
    ...
}

ちなみに、usingヘッダーを入れるのは悪い考えです。ヘッダーを含むすべての人が、必ずしもそれらの名前をグローバル名前空間にダンプすることを望んでいるわけではありません。

于 2012-09-14T10:18:09.797 に答える