Dear Kind DaniWebbers,
I am trying to overload the fstream operators (ofstream/ifstream), so that I can save a class to a 'Binary' file and also display it with cout. But the ways in which each need to be implemented is different. Please can you show me how to define different operators for each.
Here is my test class:
class CBase
{
public:
//CBase(void) {};
CBase(int i = 0,
float f = float(0.0),
double d = double(0.0),
char c = 'A') :
iMyInt(i),
fMyFloat(f),
dMyDouble(d),
cMyChar(c) {}
~CBase(void) {}
int iMyInt;
float fMyFloat;
double dMyDouble;
char cMyChar;
friend std::ostream& operator<<(std::ostream& os, CBase& obj)
{
os << obj.iMyInt << " " <<
obj.fMyFloat << " " <<
obj.dMyDouble << " " <<
obj.cMyChar;
//os.write((char *)&obj.iMyInt, sizeof(obj.iMyInt));
//os.write((char *)&obj.fMyFloat, sizeof(obj.fMyFloat));
//os.write((char *)&obj.dMyDouble, sizeof(obj.dMyDouble));
//os.write((char *)&obj.cMyChar, sizeof(obj.cMyChar));
return os;
}
friend std::istream& operator>>(std::istream& is, CBase& obj)
{
//is.read((char *)&obj.iMyInt, sizeof(obj.iMyInt));
//is.read((char *)&obj.fMyFloat, sizeof(obj.fMyFloat));
//is.read((char *)&obj.dMyDouble, sizeof(obj.dMyDouble));
//is.read((char *)&obj.cMyChar, sizeof(obj.cMyChar));
is >> obj.iMyInt >>
obj.fMyFloat >>
obj.dMyDouble >>
obj.cMyChar;
return is;
}
};
Thanks in advance.