c++ 将成员函数的输出写入文本文件



我正在尝试将类的成员函数的输出写入文本文件。我似乎无法让我的输出重载运算符按照我的意愿运行。我天真地在行中使用未识别的参数

outStream << myClass.myMemberFunction(x1, x2, results)

因为我仍然没有找到任何无需更改有关 myMemberFunction 的任何内容即可工作的方法。

下面是一个示例:

头文件

proper include guards

class myClass {
public:
bool myMemberFunction( int& x1, int& x2, std::vector<int> results);

friend ostream &operator<< (ostream& out, myClass& Class)

};

然后在

类定义源文件

proper include files
using namespace std;
using std::vector;
bool myClass::myMemberFunction(int& x1, int& x2, vector<int> results) {
int x3;
x3 = x1 + x2;
results.push_back(x3);
return true;
};
myClass& operator<< (ostream& out, myClass& myClass) {
ofstream outStream;
outStream.open("emptyFile.txt", ios::app);
if (outStream.is_open()) {
outStream << myClass.myMemberFunction(x1, x2, results);

这里重要的部分是我想输出存储在结果向量中的值

outStream.close();
}
else throw "Unable to open file";
}

有没有办法在不更改myMemberFunction的情况下做到这一点?

ofstream& operator<< (ofstream& out, const myClass& instance) {
std::vector<int> results;
instance.myMemberFunction(x1, x2, results); // x1 and x2 need to be defined
for(int i : results) {
out << i;
}
return out;
}

您需要在其他地方创建文件等

myClass classObject; // Some instance of myClass you want to output
ofstream outStream;
outStream.open("emptyFile.txt", ios::app);
if (outStream.is_open()) {
outStream << classObject; // You can output an instance of your class now
outStream.close();
}
else throw "Unable to open file";

您还需要更新头文件中的operator<<声明以返回ostream&而不是myClass&。 您确切地要做的是重载类的流运算符。因此,当您将其与流一起使用时,此方法将被调用,并且您的实现确定当您想要输出类的实例时流会发生什么。所以你不应该在那里打开一个文件。只需将成员函数的返回值输出到流并返回即可。

编辑:您还必须更改成员函数的签名以通过引用传递向量(否则填写副本(。整数不需要通过引用传递。

最新更新