简体   繁体   中英

how to use shift operator in cout statement as it is overloaded

I am quite new to c++, i know that shift operator is overloaded in c++. But as we can do shift operation inside printf in C can we do shift operation in cout statement.

Well, just try it...

#include <iostream>

int main() {
    int k = 1;
    std::cout << (k << 1) << std::endl;  // Correct shifting - notice the parentheses
    std::cout << k << 1 << std::endl;    // Wrong
    return 0;
}

Output:

2
11

What matters here is the type of the variables used for the << operator.

The parentheses causes it to be int << int which is the bitwise shifting. Without the parentheses it will be ostream << int which will write the int to the stream.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM