C++类重载写入文件

实现了一个Student类,并重载其运算符流函数。

Student.h文件:

#pragma once  //vs专用防止头文件二次引用

#include <iostream>
#include <string>
#include <fstream>

using std::string;
using std::ifstream;
using std::ofstream;

//匈牙利命名规则
class Student
{
	protected:
		string m_ID;
		string m_name;
		char m_sex;
		int m_age;
	public:
		Student();
		Student(string id,string name,char sex,int age);
		virtual ~Student();//析构函数
		void Display();
		string::size_type GetNameLength();//重载成员函数

		string GetName();
		void operator= (Student &stu);//引用与指针最好与变量靠近
		bool operator>= (Student &stu);

		friend ifstream& operator>> (ifstream &input, Student &stu); //重载流运算符使其可以写入对象
		friend ofstream& operator<< (ofstream &output,Student &stu);


};

Student.cpp文件:

#include "Student.h"

using namespace std;

Student::Student()
{
}

Student::Student(string id,string name,char sex,int age)
{
	m_ID = id;
	m_name = name;
	m_sex = sex;
	m_age = age;

}

Student::~Student()
{

}

void Student::Display()
{
	cout<<"m_ID ="<<m_ID<<endl;
	cout<<"m_name ="<<m_name<<endl;
	cout<<"m_sex ="<<m_sex<<endl;
	cout<<"m_age ="<<m_age<<endl;

}

string Student::GetName()
{
	return m_name;
}

void Student::operator= (Student &stu)
{
	this->m_ID = stu.m_ID;
	this->m_name = stu.m_name;
	this->m_age = stu.m_age;
	this->m_sex = stu.m_sex;

}

bool Student::operator>= (Student &stu)
{
	return ((this->m_age >=stu.m_age)? true:false);
}

ifstream& operator>> (ifstream &input, Student &stu)
{
	input>>stu.m_ID>>stu.m_name>>stu.m_sex>>stu.m_age;
	return input;

}
ofstream& operator<< (ofstream &output,Student &stu)
{
	output<<stu.m_ID<<" "<<stu.m_name<<" "<<stu.m_sex<<" "<<stu.m_age;
	return output;

}

main.cpp:

#include <iostream>
#include "Student.h"
#include <Windows.h>
#include <vector>
using namespace std;

int main()
{
	Student st;
	Student stu("123","tom",'B',19);
	Student stu1("123","Lom",'B',20);
	
	/*bool flag = stu1.operator>=(stu);
	cout<<flag<<endl;
	st.Display();*/
	cout<<endl;
	string str("myfile.txt");
	//fstream creat(str.c_str(),fstream::in|fstream::out|fstream::app);
 //=====对象写入文件--- 
	ofstream out(str.c_str(),ios::out|ios::trunc|ios::binary);
	if(!out.is_open())
	{
		MessageBox(NULL,L"文件打开失败!",NULL,0);
	}
	out<<stu;
	if(!out)
	{
		MessageBox(NULL,L"文件写入失败!",NULL,0);
	}
	out.close();
//======对象读取文件----
	ifstream in(str.c_str(),ios::in|ios::binary);
	if(!in.is_open())
	{
		MessageBox(NULL,L"文件打开失败!",NULL,0);
	}
	in>>st;
	if(!in)
	{
		MessageBox(NULL,L"文件读取失败!",NULL,0);
	}
	in.close();
	st.Display();
	getchar();
	return 0;

}

很久以前的代码,重新整理一下,自己也再熟悉一遍。


  • 3
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值