我试图将一个复杂对象保存到一个文件中,在复杂对象中重载<<和>>操作符,如下所示
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;
};其中人员是数据对象的数组。
我试过注释不同的部分,但是错误仍然发生,其他线程说我的重载的标题是错误的,但是我只是逐个地复制字母,所以我对此感到有点困惑。
提前谢谢。
发布于 2015-02-14 01:25:20
您对流的使用无效。当您使用流作为成员时,需要确保封装对象是不可复制的。
如果您添加了FileSave(const FileSave&) = delete; (或者声明它是私有的,而不是实现它--如果您使用的是预c++11),您将(我认为)将编译错误更改为关于FileSave的错误(因为代码可能正在某个地方复制FileSave的副本,而且由于无法复制流,所以无法实现)。
与其将流对象保持在类范围内,不如考虑在函数中定义流对象的作用域:
void demo_function()
{
using namespace std;
// "Where people is the array of the Data object"
vector<Data> people;
// load:
ifstream in{ "flatsave.elo" };
copy( istream_iterator<Data>{ in }, istream_iterator<Data>{},
back_inserter(people) );
// save:
ofstream out{ "flatsave.elo" }; // will be flushed and saved
// at end of scope
copy( begin(people), end(people),
ostream_iterator<Data>{ out, "\n" };
} // will flush out and save it and close both streams发布于 2015-02-14 01:09:33
流不是容器,而是数据流。因此,它们不能被复制,而且,在C++11之前,执行此操作的方式是它们的副本构造函数是private。
现在,由于类FileSave包含两个流,这意味着FileSave也不能被复制!财产是传递性的。因此,您必须确保您不尝试这样做,或引入一些间接围绕这些成员。
https://stackoverflow.com/questions/28511272
复制相似问题