如何在cout语句中使用shift运算符,因为它已经过载

时间:2018-02-11 07:48:50

标签: c++

我对c ++很新,我知道移位运算符在c ++中过载。但是由于我们可以在C中的printf内部进行移位操作,我们可以在cout语句中进行移位操作。

1 个答案:

答案 0 :(得分:4)

好吧,试试吧......

#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;
}

输出:

2
11

这里重要的是用于<<运算符的变量类型。

括号使它成为int << int,这是按位移位。如果没有括号,它将ostream << intint写入流。