///// 一个完整的类,包含以下操作:重载运算符 << >>,赋值转换,string模板类,fstream对二进制数据读写
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class Tperson; // declaration of Tperson class
ostream& operator << (ostream& s, Tperson& per); // declaration of function
istream& operator >> (istream& s, Tperson& per); // declaration of function
class Tperson
{
friend ostream& operator << (ostream& s, Tperson& per); //friend declartion
friend istream& operator >> (istream& s, Tperson& per); //friend declartion
string _name; //_name is Tperson's name
public:
Tperson (string n = "") { _name = n; } //default constructor
Tperson (const Tperson& per) { _name = per._name; } //copy constructor
Tperson& operator = (const Tperson& per) { _name = per._name; return *this; } //overrding assignment function //有必要进行定义,这是对象的赋值,不产生临时对象
//Tperson& operator = (string strSrc) { _name = strSrc; return *this; } //overrding assignment function 定义了构造函数就无需定义赋值转换了,会自动调用构造函数,产生临时对象,和前一个不同
void Setname (string n) { _name = n; } //set Tperson's name
string Getname () const { return _name; } //get Tperson's name
};
ostream& operator << (ostream& s, Tperson& per) //definition of overriding << function
{
s << per._name;
return s;
}
istream& operator >> (istream& s, Tperson& per) //definition of overriding >> function
{
s >> per._name;
return s;
}
//funtion to verify class Tperson
void File ()
{
Tperson per1[3] = {Tperson ("P11"),Tperson ("P2"),Tperson ("P3")};
//write binary file
ofstream outfile;
outfile.open ("c://data.dat", ios::binary);
for (int i = 0; i < 3; i++)
outfile.write ((char*)&per1[i], sizeof (per1[i]));
outfile.close ();
//read binary file
ifstream infile ("c://data.dat", ios::binary);
if (!infile)
{
cerr << "文件无法打开";
exit (1);
}
Tperson per2[3];
for ( i = 0; i < 3; i++)
infile.read ((char*)&per2[i], sizeof (per2[i]));
infile.close ();
for ( i = 0; i < 3; i++)
{
cout << "name : " << per2[i].Getname () << " " << sizeof (per2[i]) << " " << sizeof (Tperson) << endl;
}
//verify overriding and assignment functions
Tperson per ("sfg"); cin >> per;
cout << per<< endl;;
per = "LKH:KHG"; //赋值,将产生临时对象
cout << per << endl;
per = per2[2];
cout << per << endl;
Tperson per3 = Tperson ("Hey"); //强制转换
}