+ 3

How to correctly overload the << operator with seperate bodies for fstream and ostream ?

I am trying to overload the << operator for files and cout in a Complex Number Class... friend ostream& operator<<(ostream& os, const Complex& c) { std::ofstream* p_ofs = dynamic_cast<std::ofstream*>(&os); if( p_ofs == NULL ) { os.precision(6); os.setf(ios::fixed); os<<"("<<c.real<<","<<c.imag<<")"; } else { p_ofs->setf(ios::fixed); (*p_ofs)<<c.real<<" "<<c.imag; } return os; } Now, on calling cout<<Complex(2,2)<<endl; , I get (2,2) just as I wanted... But, on calling file<<Complex(2,2)<<endl; , I get (2,2) in the file, in which I wanted 2 2 ... Why is there a similarity of outputs? //I tried overloading this function for fstream, but that failed. So, I tried dynamic cast...

13th May 2017, 11:43 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
1 Réponse
0
Try. #include <typeinfo> if(typeid(&os) == typeid(std::ostream*))... else if(typeid(&os) == typeid(std::ofstream*))...
19th May 2017, 2:53 PM
Testing002