Thread: operators << and >>

  1. #1
    Performer
    Join Date
    Jan 2007
    Location
    Macedonia
    Posts
    54

    Exclamation operators << and >>

    How to overload the << and >> operator
    i have class like this:
    Code:
    class kom
    {
    private:
    int a,b;
    char d;
    float x,y;
    public:
    kom(){}
    kom(int l,int m,char n,float i,float j)
    {
    a=l; b=m; d=n; i=x; y=j;
    }
    }
    i now a litle how to do this
    Code:
    friend kom  operator<<(ostream, out_file)
    {
    cout<<a<<b<<d<<x<<y<<'\n';
    }
    i know this is not correct but i dont know the right way

  2. #2
    Ethernal Noob
    Join Date
    Nov 2001
    Posts
    1,901
    1. You declare it to be a friend only in the class body.
    Code:
    class kom
    {
    friend ostream& operator<<(ostream& out, const kom&);
    //other data
    }; //<===Don't forget the semicolon after the class declaration
    you define it elsewhere without the friend directive because outside the class it would mean it's a friend to the global scope, which wouldn't be much use

    Code:
    class kom
    {
    //other data
    };
    
    //defined outside the scope of kom
    ostream& operator<<(ostream& out, const kom&)
    {
    //don't use cout, cout is the standard output, you want 
    //to use any output stream such as a file or string stream or any
    //other stream object
      out <<a<<b<<d<<x<<y<<'\n';
      return out; //remember to return it.
    }
    now you can use it as such

    Code:
    int main()
    {
      ofStream outfile("output.txt");
      ostringstream outsstream;
      kom aKom;
      //do whatever it is you want with your class
      cout << aKom;
      outfile << aKom;
      outsstream << aKom;
      return 0;
    }
    Last edited by indigo0086; 04-06-2007 at 03:14 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Overloading fstream's << and >> operators
    By VirtualAce in forum C++ Programming
    Replies: 2
    Last Post: 04-09-2007, 03:17 AM
  2. << and >> overloading
    By Armatura in forum C++ Programming
    Replies: 2
    Last Post: 12-07-2003, 06:19 PM
  3. Overloading the << and >> operators
    By WebmasterMattD in forum C++ Programming
    Replies: 9
    Last Post: 10-15-2002, 05:22 PM
  4. << !! Posting Code? Read this First !! >>
    By kermi3 in forum Linux Programming
    Replies: 0
    Last Post: 10-14-2002, 01:30 PM
  5. << !! Posting Code? Read this First !! >>
    By kermi3 in forum C# Programming
    Replies: 0
    Last Post: 10-14-2002, 01:26 PM