|
发表于 2018-6-9 15:37:08
|
显示全部楼层
cpp的fstream并没有足够智能到足以保存类对象的的地步,所以你要么自己实现,要么借助第三方类库,下面我帮你写个一个比较简单的方法,你拿去吧
- #include <iostream>
- #include <fstream>
- #include <string>
- #include <map>
- using namespace std;
- class ceshi{
- public:
- map<int, string> obm;
- int count;
- friend ifstream& operator>>(ifstream& is, ceshi& st);
- friend ofstream& operator<<(ofstream& os, const ceshi& st);
- };
- ifstream& operator>>(ifstream& is, ceshi& st){
- is >> st.count;
-
- //如果map对象有多个的话,这里可以写个循环来循环写入
- int first;
- string second;
- is >> first;
- is >> second;
- st.obm.insert(pair<int, string>(first, second));
- return is;
- }
- ofstream& operator<<(ofstream& os, ceshi& st){
- os << st.count << " ";
- for (auto iter = st.obm.begin(); iter != st.obm.end(); iter++) {
- os << iter->first << " " << iter->second << " ";
- }
- return os;
- }
- int main() {
- ceshi c;
- c.count = 6;
- c.obm[44] = "gdagzsd";
- ofstream fout("ceshi.txt");
- fout << c;
- fout.close();
- ceshi c2;
- ifstream fin("ceshi.txt");
- fin >> c2;
- cout << c2.count << endl;
- for (auto iter = c2.obm.begin(); iter != c2.obm.end(); iter++){
- cout << iter->first << " " << iter->second << endl;
- }
- fin.close();
- return 0;
- }
复制代码 |
|