c++ - 重载 << 运算符时访问私有(private)类成员的问题

标签 c++ operator-overloading ostream

我看过一些关于这个主题的其他主题,但它们对我的帮助不是特别好。我正在创建一个打印到 .html 文件的类。我已经将 ostream 声明为 friend ,但它仍然无法访问该类的私有(private)成员。

我的 .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;
    }

任何帮助都会相当……有帮助。

最佳答案

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

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

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

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

关于c++ - 重载 << 运算符时访问私有(private)类成员的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12422367/

相关文章:

C++:隐式成员函数

C++ 运算符混合使用和优先级不是我想要的

c++ - 使用初始化列表作为函数参数实现 operator[] 的类对象示例

c++ - 无法在另一个类的迭代器类中使operator <<

c++ - 显示对 std::ostream 的输入

c++ - wxButton 不会触发事件。

java - 如何在C++中实现Java "Scanner"?

c++ - 重载赋值和加运算符

c++ - 这个 std::ostream 相关的堆栈跟踪是什么意思?

调用 std::vector::clear 时 c++ 崩溃