我最近才了解到C++类的friend关键字和序列化的用法,现在我需要一些帮助才能使其工作。C++类序列化
我没有问题序列化我的类到一个文件,它的工作很好,但是我很难试图读取这个文件到一个向量容器。我敢肯定,我需要在我的代码循环逐行阅读,但由于类有不同的类型,我想我不能使用std :: getline(),也许这种方法不会使用istream方法我实施? 样本输出文件将是:
Person 1
2009
1
Person 2
2001
0
我的代码:
class SalesPeople {
friend ostream &operator<<(ostream &stream, SalesPeople salesppl);
friend istream &operator>>(istream &stream, SalesPeople &salesppl);
private:
string fullname;
int employeeID;
int startYear;
bool status;
};
ostream &operator<<(ostream &stream, SalesPeople salesppl)
{
stream << salesppl.fullname << endl;
stream << salesppl.startYear << endl;
stream << salesppl.status << endl;
stream << endl;
return stream;
}
istream &operator>>(istream &stream, SalesPeople &salesppl)
{
stream >> salesppl.fullname;
stream >> salesppl.startYear;
stream >> salesppl.status;
// not sure how to read that empty extra line here ?
return stream;
}
// need some help here trying to read the file into a vector<SalesPeople>
SalesPeople employee;
vector<SalesPeople> employees;
ifstream read("employees.dat", ios::in);
if (!read) {
cerr << "Unable to open input file.\n";
return 1;
}
// i am pretty sure i need a loop here and should go line by line
// to read all the records, however the class has different
// types and im not sure how to use the istream method here.
read >> employee;
employees.push_back(employee);
顺便说一句,我知道Boost库有很大的序列化类,但是我在努力学习如何系列化现在可以使用STL库。 非常感谢您为我提供的任何帮助以及让我走上正轨!
非常感谢你!!!! 这帮了很多!现在我明白我做错了什么更好。 另外,我对ws一无所知,我一直在想如何做很久!非常感谢! – nmuntz 2009-04-15 00:29:35