实现了一个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;
}
很久以前的代码,重新整理一下,自己也再熟悉一遍。