【发布时间】:2017-09-08 09:01:35
【问题描述】:
当我在重载的operator= 末尾添加return 语句时,编译器会抛出错误。它说:
'File::File(const File&)' 被隐式删除,因为默认定义格式不正确
但是,当我删除 return 语句(和类型说明符)时,没问题。
class File : public Document {
private:
fstream mainFile;
string drive, folder, fileName, fullPath;
protected:
public:
File(string d, string f, string fn, string txt = "NULL") : Document(txt) {
drive = d;
folder = f;
fileName = fn;
if(fileName.find(".txt") == -1) {
fileName.append(".txt");
}
fullPath = drive + ":/" + folder + "/" + fileName;
mainFile.open(fullPath.c_str());
mainFile << txt;
}
File() : Document() {
drive = folder = fileName = "NULL";
fullPath = drive + ":/" + folder + "/" + fileName;
}
File operator = (File & a) {
this->getDrive() = a.getDrive();
this->getFolder() = a.getFolder();
this->getFileName() = a.getFileName();
this->getText() = a.getText();
this->fileName = a.fileName;
return a;
}
};
【问题讨论】:
-
顺便说一句,
this->符号不是必需的。仅当局部变量或参数与成员具有相同名称时才使用它。您可以更改参数和局部变量以避免this->。this->也不需要执行类方法。 -
在查看
find的结果时优先使用std::string::npos而不是-1。 -
您正在尝试返回传入引用的副本。该类不知道如何构造副本。你需要写一个拷贝构造函数。
-
默认定义格式不正确,因为默认定义会按成员进行复制,而无法复制
fstream对象。因此,编译器不知道如何处理mainFile成员。