can't overload << as member function

arkangel's Avatar, Join Date: Aug 2008
Light Poster
any idea why I can't overload << as member function
i.e
Code:
template<typename T>
class Simple{
    T  A,B;
public:
/* Constructors and destructors  */
    T  getA(){return A;}
     T  getB(){return B;}

   ostream& operator(ostream& os){ return  os<<A<<"-"<<B; } 
   // this doesn't work

}


template<typename T>
ostream& operator(ostream& os, Simple<T> P )
{ return  os<<P.getA()<<"-"<<p.getB(); } 
//this works

I can overload the +, - inside and outside the class.

But << and most probably >> has to be implemented as esternal function , why so ? any idea
0
arkangel's Avatar, Join Date: Aug 2008
Light Poster
sorry for the typo . it should read in both operator lines:
"ostream& operator<<(ostream& os, Simple<T> P )"
0
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
Because they are not the internal members of the class. the format in which you specify is such that the function needs to be external.

cout<<YourVariable<<endl;

Now if you get into the operator overloading this should be

OutputClassFunction.Operator <<(YourVariable)

And so you need the first parameter as IO class variable and so you cannot have the function as internal.