can't overload << as member function

Discussion in 'C++' started by arkangel, Aug 24, 2008.

  1. arkangel

    arkangel New Member

    Joined:
    Aug 11, 2008
    Messages:
    6
    Likes Received:
    0
    Trophy Points:
    0
    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 :)
     
  2. arkangel

    arkangel New Member

    Joined:
    Aug 11, 2008
    Messages:
    6
    Likes Received:
    0
    Trophy Points:
    0
    sorry for the typo . it should read in both operator lines:
    "ostream& operator<<(ostream& os, Simple<T> P )"
     
  3. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
    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.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice