我最近才瞭解到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