How does 'cout' & 'cin' use multiple operators?

The class operators of 'std::cout' and 'std::cin' can use multiple operators; for example:

std::cout << "3 + 2 = " << 5

'"3 + 2 = "' is a string type and '5' is a int type variable. These variables are combined together to form a character array which is output to the console window.

My question to you is how can this be done via editing or overloading only the equivalent 'cout' class in this example, or can it not be done; in which case how have they done it and what is the coding behind the class?

Help would be much obliged.
Thanks in advance.
Last edited on
'"3 + 2 = "' is a string type and '5' is a int type variable. These variables are combined together to form a character array which is output to the console window.
Not quite. operator<<() has a few overloads. One of which takes a const char * as the right hand operand. All those overloads return an std::ostream & (a reference to the left hand operand), so it's not that the 5 is converted to a string and then appended to the previous one, it's something more like this:
(std::cout <<"3 + 2 = ")<<5;
The overload for C strings merely sends each character to the stream. The overload for integers first converts the integer to a string and then sends that to the stream

editing or overloading only the equivalent 'cout' class
Classes can't be overloaded and std::cout is not a class. It's an object.
Thanks for your reply.

Could you or someone else elaborate with an example; just so I'm 100% clear?
(Not necessarily a full program just the relevent bits)
An example could be overloading the << operator for a custom type:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
struct Person // Sample type
{
    string name, surname;
    Person ( const string &n, const string &s) : name(n), surname(s) {}
};

ostream & operator << ( ostream &os, const Person &p )
{
   os << p.name << ' ' << p.surname; // send stuff to the stream
   return os; // return the stream which now contains the characters representing the struct
}



Person sample ( "Foo", "Bar" );
cout << sample; //display "Foo Bar"
ofstream file ( "text.txt");
file << sample; // writes "Foo Bar" to the file 
Oh - I get it now!
Thank you for both of yours' help - it seems so simple now :)

I had seen examples dotted around like that but never knew what it was used for.

Nonetheless - Thank You.
Topic archived. No new replies allowed.