C++实现向文件输出对象并读取对象

#include <iostream>
#include <fstream>
using namespace std;

class Dog
{
public:
    Dog(int a,int b):weight(a),age(b){}
    ~Dog(){}
    int getWeight(){return weight;}
    int getAge(){return age;}
    void setWeight(int w){weight = w;}
    void setAge(int age){(*this).age = age;}
private:
    int weight,age;
};
int main()
{
    ofstream fout("1.txt",ios_base::out|ios_base::binary);
    Dog dog1(5,10);
    fout.write((char*)&dog1,sizeof dog1);
    fout.close();

    ifstream fin("1.txt",ios_base::in|ios_base::binary);
    Dog dog2(2,2);
    cout <<dog2.getWeight() << "\n" << dog2.getAge() <<endl;
    fin.read((char*)&dog2,sizeof dog2);
    cout <<dog2.getWeight() << "\n" << dog2.getAge() <<endl;
    fin.close();
    return 0;
}
文件名部分也可以考虑用char filename[]来实现
posted @ 2021-03-13 12:46  Weisswire  阅读(189)  评论(0编辑  收藏  举报