In the example below, what exactally is the <<
operator doing? I'm guessing it is not a bitwise operator.
std::cout << "Mouse down @ " << event.getPos() << std::endl;
I understand what the code will do here: Use standard out, send this text, send an end of line. Just I've never come accross the use of this << apart from on raw binary.
I'm starting out with C++. And, as an operator of sorts, it's hard to search for a description of this and what it means. Can someone enlighten me and/or give me a pointer as to what to google for?
Thanks Ross
Description. This operator shifts the first operand the specified number of bits to the left. Excess bits shifted off to the left are discarded. Zero bits are shifted in from the right.
Explanation: Left Shift Operator << shifts bits on the left side and fills Zeroes on the Right end.
Left Shift and Right Shift Operators in C/C++ Takes two numbers, left shifts the bits of the first operand, the second operand decides the number of places to shift.
The answer is: The <<
operator does left shifts by default for integral types, but it can be overloaded to do whatever you want it to!
This syntax for piping strings into a stream was first (I think) demonstrated in C++ inventor Bjarne Stroustroup's eponymous book The C++ Programming Language. Personally, I feel that redefining an operator to do IO is gimmicky; it makes for cool-looking demo code but doesn't contribute to making code understandable. Operator overloading as a technique has been widely criticized in the programming language community.
EDIT: Since nobody else has mentioned this yet:
operator<<
is defined in the ostream
class, of which cout
is an instance. The class definition sits in the iostream library, which is #include
'd as <iostream>
.
The operator<<
is being overloaded. Check out Operator Overloading.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With