10.13

#include 
#include 
#include 

using namespace std;

class Stu
{
    friend ofstream& operator<<(ofstream& out, const Stu& s);
    friend ostream& operator<<(ostream& o, const Stu& s);
    friend ifstream& operator>>(ifstream& ifs,  Stu& s);
private:
    string name;
    int age;

public:
    Stu() {}
    Stu(string name, int age): name(name), age(age) {}
//    Stu(const Stu& other): name(other.name), age(other.age) {}
//    Stu& operator=(const Stu& other)
//    {
//        name = other.name;
//        age = other.age;
//        return *this;
//    }
};

ofstream& operator<<(ofstream& ofs, const Stu& s)
{
    ofs << s.name << "\t" << s.age << endl;
    return ofs;
}
ifstream& operator>>(ifstream& ifs,  Stu& s)
{
    ifs >> s.name;
    ifs >> s.age;
    return ifs;
}
ostream& operator<<(ostream& out, const Stu& s)
{
    out << s.name << "\t" << s.age << endl;
    return out;
}
int main()
{
    Stu s1("zhang", 18);
    Stu s2("lisi", 20);
    Stu s3("wangwu", 22);

    vector v;
    vector::iterator iter = v.begin();
    v.push_back(s1);
    v.push_back(s2);
    v.push_back(s3);

    ofstream ofs;
    ofs.open("D:\\23071_C++\\C++\\day7\\stu.txt", ios::out);
    for(iter = v.begin(); v.end() != iter; iter++) {
        ofs << *iter;
    }
    ofs.close();

    ifstream ifs;
    ifs.open("D:\\23071_C++\\C++\\day7\\stu.txt", ios::in);
    vector v1;
    Stu t;
    while (ifs >> t ) {
        v1.push_back(t);
    }

    for(iter = v1.begin(); v1.end() != iter; iter++) {
        cout << *iter;
    }

    ifs.close();
    return 0;
}

你可能感兴趣的:(c++,开发语言)