C++ fstream 写入重载的“<<”,但失败,文件仍然为空
#include <iostream>
#include <fstream>
#include <string.h>
#include <cstdlib>
#include <ctype.h>
#include <stdlib.h>
using namespace std;
class W_File_of_Int : public ofstream {
private:
ofstream _fout;
public:
W_File_of_Int(const char* nom_fic)
{
ofstream _fout(nom_fic, ios::out | ios::binary);
cout << "\n\tfile of int to write is ready";
}
~W_File_of_Int()
{
cout << "\n\tDestruction of file to write\n";
_fout.close();
}
int tellp() { return ofstream::tellp(); }
W_File_of_Int& operator<<(int i)
{
_fout.write((char*)&i, sizeof(int));
return *this;
}
};
int main()
{
W_File_of_Int f_out("essai.fic");
if (!f_out) {
cerr << "\nErreur dansla creation de 'essai.fic'\n";
return 1;
}
for (int i = 0; i <= 10; i++) // Ecriture de 11 entiers dans le fichier
f_out << i;
cout << f_out.tellp() << "\n\telements sont ecrits dans le fichier.\n";
// affiche: 11 elements sont ecrits dans le fichier.
f_out.close();
return 0;
}
我尝试了很多次,例如make int to&amp; int,它只是没有
用过载的工作写入“&lt;&lt;”,但失败了,文件仍然为空。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的构造函数可以访问 3 个不同的
ofstream
实例:this->_fout
_fout
。您可能应该仅使用基类,为此您需要更改构造函数:
Your constructor has access to 3 different
ofstream
instances:this->_fout
_fout
.You should probably use the base class only, for which you would need to change the constructor:
在这里您创建了两个 ofstream : _fout 和基类;
你应该选择一个
here you create two ofstream : _fout AND the base class;
you should choose one