我看过一些关于这个主题的其他主题,但它们对我的帮助不是特别好。我正在创建一个打印到 .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/