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 << "ntfile of int to write is ready";
}
~W_File_of_Int()
{
cout << "ntDestruction of file to writen";
_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() << "ntelements sont ecrits dans le fichier.n";
// affiche: 11 elements sont ecrits dans le fichier.
f_out.close();
return 0;
}

我试过很多次,比如把int变成&int,它就是不起作用

用过载的"写入"<lt&";,但失败,文件仍然为空。

您的构造函数可以访问3个不同的ofstream实例:

  • 基类
  • 成员变量this->_fout
  • 局部变量_fout

您可能应该只使用基类,为此您需要更改构造函数:

W_File_of_Int(const char* nom_fic) :
ofstream(nom_fic, ios::out|ios::binary) // call base class constructor
{
cout << "ntfile of int to write is ready";
}
class W_File_of_Int :  public ofstream
{
private:ofstream _fout;
.......

在这里创建两个stream_fout AND基类;

你应该选择一个

相关内容

最新更新