我创建了一个类,允许我使用 operator[] 获取和更改文件的字符。问题是,每次我执行程序时,文件都会由于某种原因变为空。为什么会发生?
#include <iostream>
#include <fstream>
using namespace std;
class FileChar;
class File {
private:
ofstream* o_stream;
ifstream* i_stream;
public:
File(char* s);
~File();
void setChar(char c,int position);
FileChar operator[](int index);
};
// ********************************************* class FileChar *****************************
class FileChar {
private:
char c;
int position;
File* file;
public:
// --- Constructor ---
FileChar(char c,int position,File* file) :
c(c),position(position),file(file)
{}
// --- cast char ---
operator char() const {
return c;
}
// --- getChar ---
char getChar() const {
return c;
}
// --- operator= ---
FileChar& operator=(char new_c) {
cout << "operator=" << endl;
c = new_c;
file->setChar(c,position);
return *this;
}
};
ostream& operator<<(ostream& os,const FileChar& c) {
cout << "Fdsf";
os << c.getChar();
return os;
}
// ************************************************* class File *******************************
// --- Constructor ---
File::File(char* s) {
o_stream = new ofstream(s);
i_stream = new ifstream(s);
}
// --- Destructor ---
File::~File() {
o_stream->close();
i_stream->close();
delete i_stream;
delete o_stream;
}
// --- setChar ---
void File::setChar(char c,int position) {
cout << "setChar" << endl;
o_stream->seekp(position,ios_base::beg);
o_stream->put(c);
}
// --- operator[] ---
FileChar File::operator[](int index) {
cout << "get index " << index << endl;
i_stream->seekg(index,ios_base::beg);
char c[2];
i_stream->get(c,1);
FileChar f(c[0],index,this);
return f;
}
int main() {
File file("text.txt");
file[0] = 'H';
return 0;
}