首页 > 技术文章 > 文件与对象

area-h-p 2019-02-25 13:24 原文

在面向对象的程序设计中,信息总是放在对象的数据成员里。这些信息应该保存在文件内。当程序开始运行时,就要由打开的文件重新创建对象。在运行过程中,放在对象的数据成员里的信息得到利用和修改。运行结束时必须把这些信息重新保存到文件内,然后关闭文件。

首先我们在项目文件夹下建立一个Data.dat文件

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

class Exchange
{
friend ostream& operator<<(ostream &out, const Exchange &a);
private:
    int Gold;
    int Diamond;
public:
    Exchange():Gold(0),Diamond(0)
    {
        ifstream ifile("Data.dat", ios::in);
        if(!ifile)
        {
            cerr<<"Open file error"<<endl;
            exit(1);
        }
        ifile>>this->Gold>>this->Diamond;
        ifile.close();
    }
    Exchange(int G, int D):Gold(G),Diamond(D)
    {}
    void Adjust(int g, int d);
    ~Exchange()
    {
        ofstream ofile;
        ofile.open("Data.dat",ios::out);
        if(!ofile)
        {
            cerr<<"Open file error."<<endl;
            exit(1);
        }
        ofile<<this->Gold<<" "<<this->Diamond;
        ofile.close();
    } 
};
void Exchange::Adjust(int g, int d)
{
    this->Gold = g;
    this->Diamond = d;
}
ostream& operator<<(ostream &out, const Exchange &a)
{
    out<<a.Gold<<" "<<a.Diamond;
    return out;
}
void main()
{
    Exchange a;
    cout<<a<<endl;
    a.Adjust(10,20);
}

运行第二遍时会输出10 20,说明数据信息在一次程序运行结束后已经被保存在文件内。

第一遍

第二遍

使数据信息保存在文件内是析构函数的工作,构造函数负责将数据信息从文件内读出来。

 

推荐阅读