Understanding operator<<


I've hit one of those walls, where I don't understand something.

ostream& operator<<

I don't understand how this works, I know its used to print text, instead of cout, but I don't know how it works. Does anyone know any tutorials, websites or books that explain this function.
Ostream is a class, cout is an object of ostream class.
http://www.cplusplus.com/reference/iostream/cout/

If you want to have a class so you can "output" it with an ostream object you need to overload the << operator.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>

class object
{
   public:
   
   object(int v): val(v) {};

   friend std::ostream & operator<<(std::ostream & op, const object & obj)
   {
       op << "The value is ";
       op << obj.val;
       return op;
   }
   
    private:
    int val;

};

int main(int argc, char ** argv)
{
    object something(10);
    std::cout<<something;

    return EXIT_SUCCESS;
}


Output:
The value is 10 
Last edited on
Topic archived. No new replies allowed.