How to correctly overload the << operator with seperate bodies for fstream and ostream ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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
Kinshuk Vasisht
Kinshuk Vasisht - avatar
1 Answer
0
Try. #include <typeinfo> if(typeid(&os) == typeid(std::ostream*))... else if(typeid(&os) == typeid(std::ofstream*))...
19th May 2017, 2:53 PM
Testing002