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() << "
" << dog2.getAge() <<endl;
    fin.read((char*)&dog2,sizeof dog2);
    cout <<dog2.getWeight() << "
" << dog2.getAge() <<endl;
    fin.close();
    return 0;
}
文件名部分也可以考虑用char filename[]来实现
原文地址:https://www.cnblogs.com/Jesse-Cavendish/p/14528356.html