如何在COUT语句中使用移动运算符

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

本文关键字:移动 运算符 语句 COUT      更新时间:2023-10-16

我是C 的新手,我知道C 中的Shift Operator被超载。但是,正如我们如何在C中的printf语句中进行换档操作一样,我们可以在Cout语句中进行类似的换档操作。

好吧,尝试一下...

#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 << int,它将将int写入流。