【发布时间】:2015-02-14 01:04:27
【问题描述】:
我正在尝试将复杂对象保存到文件中,我正在像这样重载复杂对象中的 > 运算符
class Data {
public:
string name;
double rating;
friend std::ostream& operator<<(std::ostream& o, const Data& p)
{
o << p.name << "\n";
o << p.rating << "\n";
return o;
}
friend std::istream& operator>>(std::istream& o, Data& p)
{
o >> p.name >> p.rating;
return o;
}
}
然后我使用运算符尝试将对象数组保存到文件中。 这是包含所有文件相关方法的类:
class FileSave
{
public:
FileSave()
{
openFile();
load();
}
~FileSave()
{
if(editm)
outfile.close();
else
infile.close();
}
void openFile()
{
if(editm)
outfile.open("flatsave.elo", ios::out | ios::binary);
else
infile.open("flatsave.elo", ios::in | ios::binary);
}
void closeFile()
{
if(editm)
outfile.close();
else
infile.close();
}
void save()
{
changemode(true);
outfile << people << endl;
}
void load()
{
changemode(false);
for(int i=0; i < 10; i++)
{
infile >> people[i];
}
}
void changemode(bool editmode)
{
if(editm != editmode)
{
closeFile();
editm = editmode;
openFile();
}
}
private:
ofstream outfile;
ifstream infile;
bool editm = false;
};
其中 people 是 Data 对象的数组。
我已经尝试注释掉各种位,但错误仍然存在,其他线程说我的超载标题是错误的,但我只是一个字母一个字母地复制,所以我对此有点困惑。
提前致谢。
【问题讨论】:
-
给我们完整的错误信息。
-
您正在尝试在某处复制流(或
FileSave,也许)。 -
非常模糊的问题。我可以猜出你的问题并告诉你问题是什么,但这不是一个好帖子。