Console C++ - Overloading Streams
I don't like streams. Personally, I think that they are a very bad idea.
That said, most C++ courses require the use of streams.
Talk about one problem after another - at any rate, I hope this helps.
Overloading Streams
When streams are overloaded to work with classes,
they must be declared as friend methods if you want them
to have access to private properties.
This "example" is based on working code, but has been modifed
to be more generic.
Basically, it reads a file which has string string integer
repeated multiple times.
However, several constants and functions are missing and this code will not execute.
Maybe, I'll improve it later.
Header file - abcd.h
#include
#include
class abcd_class
{
public:
abcd_class();
virtual ~abcd_class();
friend ifstream & operator >>(ifstream &ins, abcd_class &a_abcd);
friend ostream & operator <<( ostream &outs, const abcd_class &a_abcd);
private:
int Some_Value;
string String_1;
string String_2;
};
C++ file - abcd.cpp
// This reads data from a file
ifstream & operator >>(ifstream &ins, abcd_class &a_abcd)
{
// In the original code, each variable was one line of text
// However, the code to accomplish that is not here
ins >> a_abcd.String_1 >>
a_abcd.String_2 >>
a_abcd.Some_Value ;
return ins;
}
Header file - xyz.h
#include
#include
#include "abcd.h"
class xyz_class
{
public:
xyz_class();
virtual ~xyz_class();
int return_score();
friend ostream & operator <<( ostream &outs, const xyz_class &a_xyz);
friend ifstream & operator >>(ifstream &ins, xyz_class &a_xyz);
private:
int Var1;
int num_of_items;
abcd_class *Some_Array[MAX];
};
C++ file - xyz.cpp
// This writes to the console
ostream & operator << (ostream & outs, const xyz_class &a_xyz)
{
for(int i=0;i<5;i++)
{
outs << a_xyz.var1 * i << endl;
}
return outs;
}
// This reads data from a file
ifstream & operator >>(ifstream &ins, xyz_class &a_xyz)
{
abcd_class * abcd_1;
while(ins.eof()==0)
{
abcd_1= new abcd_class ;
ins >> *abcd_1; // This calls the overloaded stream operator in abcd_class
a_xyz.Some_Array[a_xyz.num_of_items] = abcd_1;
a_xyz.num_of_items++;
}
return ins;
}
C++ file - MainApp.cpp
#include
#include
#include "xyz.h"
int main()
{
xyz_class xyz_1;
ifstream infile;
infile.open("filename");
if(infile.eof()==0) // There are better ways to do this
{
cout << "Fatal error! file not found.\n";
exit (1);
}
infile >> xyz_1; // This calls the overloaded operator
infile.close();
return 0;
}
Notice that this example uses regular header files (they end in ".h") and not templates.
The namespaces associated with templates cause
all sorts of additional problems.
Author: Robert Clemenzi -
clemenzi@cpcug.org