Advertisement
cd62131

redefine operator

Jan 27th, 2014
264
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.78 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdlib>
  3. #include <string>
  4. #include <fstream>
  5. #include <vector>
  6. using namespace std;
  7. class Chara {
  8. public:
  9.   string name;
  10.   int HP;
  11.   friend ostream &operator<<(ostream &, Chara);
  12.   friend istream &operator>>(istream &, Chara &);
  13. };
  14. ostream &operator<<(ostream &out, Chara c) {
  15.   out << c.name << " " << c.HP;
  16.   return out;
  17. }
  18. istream &operator>>(istream &in, Chara &c) {
  19.   in >> c.name >> c.HP;
  20.   return in;
  21. }
  22. int main() {
  23.   vector<Chara> ch;
  24.   ifstream fin("chara.txt");
  25.   if (!fin) {
  26.     cerr << "指定したファイルが見つかりません" << endl;
  27.     exit(1);
  28.   }
  29.   while (fin) {
  30.     Chara c;
  31.     fin >> c;
  32.     if (c.name != "") ch.push_back(c);
  33.   }
  34.   fin.close();
  35.   for (Chara c: ch) cout << c << endl;
  36.   return 0;
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement