【发布时间】:2009-04-14 23:43:39
【问题描述】:
我最近了解了 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 库进行序列化。 非常感谢您为我提供的任何帮助并让我走上正轨!
【问题讨论】:
标签: c++ serialization