C++ 学习笔记(27)文件与对象

文件在构造函数中打开,并创建对象;在析构函数中保存和关闭文件,并撤销对象。

#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;

		ifile.clo***plex(int real, int imag) : m_real(real),m_imag(imag){

	}
	~Complex(){
		ofstream ofile;
		//写文件
		ofile.open("Data.dat",ios::out);
		if(!ofile){
			cerr<<"Open File Fail!"<<endl;
			exit(1);
		}
		ofile<<m_real<<" "<<m_imag;
		ofile.close();
	}
public:
	void 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;
}

void main(){
	Complex c(1,2);
	cout<<c<<endl;
	c.SetComplex(100,200);
	cout<<c<<endl;
}

版权声明:本文为博主原创文章,如有错误,恳请大家在评论区指出,在下不胜感激~如要转载注明出处即可~

全部评论

相关推荐

11-15 18:39
已编辑
西安交通大学 Java
全村最靓的仔仔:卧槽,佬啥bg呢,本也是西交么
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务