C++使用运算符重载拼接文件时提示无法为fstreambase等类生成operator=
错误原因及修复方案
核心错误:流对象禁止拷贝赋值
你定义的myfile类中将fstream file作为成员变量,而C++所有IO流类(fstreambase、istream、ostream都是其基类)原生不支持拷贝和赋值操作。
当你执行f3=f1+f2语句时,编译器会自动为myfile生成默认的赋值运算符函数,这个函数会尝试逐个拷贝类的所有成员,到file成员时因为流对象没有可用的operator=,就触发了你看到的三个编译错误。
同时你的operator+返回myfile对象时会调用默认拷贝构造函数,同样会尝试拷贝file成员,也是潜在的报错点。
最优解决方案
因为你代码中的file成员每次都是临时打开、使用完立即关闭,完全不需要作为类成员长期持有,直接把fstream file;从类成员定义中删除,所有用到文件流的地方都改为函数内部的局部变量即可,从根源上避开流对象拷贝的问题。
其他代码问题
operator+实现不完整:目前只写入了第一个文件的内容到file3,还需要补充第二个文件的读取写入逻辑。- 读取文件的逻辑有bug:
while(file)的写法会多写入一个无效的EOF字符,改为while(file.get(ch))判断读取成功再写入更稳妥。 - 注意变量命名:
operator+中局部流对象命名和参数命名接近,容易出现拼写错误。
适配TurboC3的修正后代码
#include<iostream.h> #include<conio.h> #include<string.h> #include<fstream.h> class myfile { // 删掉了fstream成员,改为各函数内局部变量 char filename[10],data[50]; public: myfile() { //cout<<"File3 created\n"; } myfile(char *fn) { strcpy(filename,fn); } void accept() { fstream file; // 局部流对象 cout<<"\nEnter data for file "<<filename<<" :\n"; cin.getline(data,50); file.open(filename,ios::out); file<<data; file.close(); } void display() { fstream file; // 局部流对象 char ch; cout<<"Contents of "<<filename<<" :\n"; file.open(filename,ios::in); while(file.get(ch)) // 修正读取判断逻辑 { cout<<ch; } file.close(); cout<<endl; } myfile operator+(myfile &f2) { myfile f3("file3.txt"); fstream file1,file2,file3_stream; // 改名避免和f3对象混淆 file3_stream.open(f3.filename,ios::out); char ch; // 写入第一个文件内容 file1.open(this->filename,ios::in); while(file1.get(ch)) { file3_stream<<ch; } file1.close(); // 补充写入第二个文件内容 file2.open(f2.filename,ios::in); while(file2.get(ch)) { file3_stream<<ch; } file2.close(); file3_stream.close(); return f3; } }; void main() { clrscr(); myfile f1("file1.txt"); myfile f2("file2.txt"); myfile f3("file3.txt"); f1.accept(); f1.display(); f2.accept(); f2.display(); f3=f1+f2; f3.display(); getch(); }
可选替代方案(保留fstream成员)
如果你一定要保留fstream作为类成员,就需要手动实现拷贝构造函数和赋值运算符,跳过流对象的拷贝逻辑:
// 拷贝构造函数 myfile(const myfile &other) { strcpy(filename, other.filename); strcpy(data, other.data); // 不拷贝fstream成员 } // 赋值运算符重载 myfile& operator=(const myfile &other) { if(this == &other) return *this; strcpy(filename, other.filename); strcpy(data, other.data); // 不赋值fstream成员 return *this; }
将上述两个函数添加到myfile的public区域即可解决编译错误。
内容的提问来源于stack exchange,提问作者chirag_9121
相关产品推荐
相关产品推荐

