Hi,
I am trying to simplify initialising objects from file and writing objects to file by overloading the "<<" and ">>" operators.
I have two classes, a nesting class and the nested class, the latter comprising two floats. The nested class forms and STL vector
class beamlets{
float left,right;
...
};
class dCP{
float d,M,g,c,u;
std::vector<beamlet> beamlets;
.
.
.
};
Thus I need something like the following (I want to use iterators, if possible)
ostream& operator<< (ostream &out, const dCP &dcp)
{
// Since operator<< is a friend of the dicomCP class, we can access
// dicomCP's members directly.
out << dcp.d << "\n" << dcp.M << dcp.g << "\n" <<
dcp.c << "\n" <<
dcp.u << "\n";
return out;
}
ostream & operator << (ostream &out, const std::vector<beamlet> &b)
std::ostream out1,out2;
for (b::const_iterator it=b.begin();it!=b.end();++b){
if (it!=b.end()-2) out1 << it.left << "," << it.right << ",\n";
else out2 << it.left << "," << it.right << "\n";
out << out1 << out2;
return out;
}
The first operator output the "header" information and the second outputs the body of the STL vector. I then need to chain these operators to output data from a file into the object... something like
// dCP object d contains beamlets
dCP d;
std::ofstream fileOut(file_out.c_str());
fileOut << d << d.beamlets;
Am I going about this the correct way? If not is there a better (more efficient, robust or elegant way) of achieving this?
Many thanks
Mark