文件与对象:
在面向对象的程序设计中,信息总是放在对象的数据成员里。这些信息最终应该保存到文件中。
当程序开始运行时,就要由打开的文件重新创建对象。
在运行过程中,放在对象的数据成员里的信息得到利用和修改。
磁盘文件打开时建立的内部文件流是在运行时动态分配的资源。
在面向对象的C++程序设计中,文件应该在构造函数中打开,并创建对象;
对文件而言,释放资源同时包括将对象中的信息再次存入磁盘文件。
在程序运行过程中,应该将信息适时保存到相应的磁盘文件中,以免数据意外丢失。
<span style="font-size:18px;">#include <iostream>
#include <fstream>
using namespace std;
class Complex;
ostream& operator<<(ostream &out,const Complex &c);
class Complex
{
friend ostream& operator<<(ostream &out,const Complex &c);
public:
Complex():m_real(0),m_imag(0) //在构造函数中从文件读数据
{
ifstream ifile;
ifile.open("Data,dat",ios::in);
if(!ifile)
{
cerr<<"Open File Fail"<<endl;
exit(1);
}
ifile>>m_real>>m_imag>>endl;
ifile.close();
}
Complex(int real, int imag):m_real(real),m_imag(imag)
{}
~Complex() //在析构函数中写保存数据,关闭文件
{
oftream ofile;
ofile.open("Data.bat",ios::out);
if(!ofile)
{
cerr<<"Open File Fail"<<endl;
exit(0);
}
ofile<<m_real<<m_imag<<endl;
ofile.close();
}
public:
SetComplex(int real, int imag)
{
m_real = real;
m_imag = imag;
}
private:
int m_real;
int m_imag;
};
ostream& operator<<(ostream &out,const Complex &c)
{
out<<"("<<c.m_real<<","<<c.m_imag<<")";
return out;
}
int main()
{
Complex c(1,2);
cout<<c<<endl;
c.SetComplex(10,20);
cout<<c<<endl;
return 0;
}</span>