user1671033
user1671033

Reputation: 47

Problems gaining access to the private class members while overloading the << operator

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.

Upvotes: 1

Views: 130

Answers (1)

Mike Seymour
Mike Seymour

Reputation: 254431

The friend declaration inside the class places the operator in the surrounding namespace (wilsonOutput). Presumably, your implementation is not in that namespace; in that case, it declares a separate overload of the operator in whichever namespace you've put it in, and that overload is not a friend of the class.

You need to specify the namespace when you implement it:

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

By the way, it's a bad idea to put using in a header; not everyone who includes the header will necessarily want those names dumped into the global namespace.

Upvotes: 3

Related Questions