1

I've seen some other threads on this topic, but they haven't been able to help me particularly well. I'm creating a class that prints out to a .html file. I've declared ostream as friend, but it still isn't getting access to the private members of the class.

my .h file

    #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

and this is what I have in my main.cpp (but not in the main code block) to implement the overload.

    // 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;
    }

Any help would be rather... helpful.

4

1 回答 1

3

类内的friend声明将操作符放置在周围的命名空间 (wilsonOutput ) 中。据推测,您的实现不在该名称空间中;在这种情况下,它会在您放入的任何命名空间中声明运算符的单独重载,并且该重载不是该类的朋友。

实现时需要指定命名空间:

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

顺便说一句,放在using标题中是个坏主意。不是每个包含标题的人都一定希望将这些名称转储到全局命名空间中。

于 2012-09-14T10:18:09.797 回答