Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/forums/cpp/)
-   -   can't overload << as member function (http://www.go4expert.com/forums/overload-function-t13217/)

arkangel 25Aug2008 00:54

can't overload << as member function
any idea why I can't overload << as member function

template<typename T>
class Simple{
    T  A,B;
/* 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 :)

arkangel 25Aug2008 00:56

Re: can't overload << as member function
sorry for the typo . it should read in both operator lines:
"ostream& operator<<(ostream& os, Simple<T> P )"

shabbir 25Aug2008 09:12

Re: can't overload << as member function
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.


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.

All times are GMT +5.5. The time now is 06:41.