1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

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,276
    Likes Received:
    364
    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