在系统加载的时候,从构造函数中读入数据
在系统结束的时候,在析构函数中存储数据
#include <iostream>
#include<fstream>
using namespace std;
class Complex
{
private:
int real;
int img;
public:
Complex();
Complex(int r,int i):real(r),img(i){};
void SetComplex(int r=0,int i=0);
~Complex();
friend ostream& operator<<(ostream& out,Complex c);
};
Complex::Complex()
{
ifstream inputdata;
inputdata.open("data.ini",ios::in);//系统加载,读入初始化数据
if(!inputdata)
{
cerr<<"open data.ini failure" <<endl;
exit(0);
}
inputdata>>real>>img;
inputdata.close();
}
Complex::~Complex()
{
ofstream outputdata;
outputdata.open("data.ini",ios::out);//程序结束后,把数据存入data.ini
if(!outputdata)
{
cerr<<"save data.ini failure" <<endl;
exit(0);
}
outputdata<<real<<" "<<img;
outputdata.close();
}
void Complex::SetComplex(int r,int i)
{
this->real = r;
this->img =i;
}
ostream& operator<<(ostream& out,Complex c)
{
out<<"("<<c.real<<","<<c.img<<")"<<endl;
return out;
}
int main()
{
Complex c;
cout<<c<<endl;
c.SetComplex(10086,10000);
return 0;
}