<< 操作符

n <<  2;

在C中:     将整数 n 按位左移 2 位。

在C++中: 将变量 / 常量对象左移到一个对象里面。

#include <stdio.h>

const char endl = '
';   // 定义换行符常量

class Console
{
public:
    Console& operator << (int i)
    {
        printf("%d", i);    
        return *this;
    }
    Console& operator << (char c)
    {
        printf("%c", c); 
        return *this;
    }
    Console& operator << (const char* s)
    {
        printf("%s", s); 
        return *this;
    }
    Console& operator << (double d)
    {
        printf("%f", d);    
        return *this;
    }
};

Console cout;  // cout对象就代表控制台

int main()
{
    cout << 1 << '
';          // 将常量1左移到cout对象中,调用函数 operator <<(int i); 函数返回cout对象。
                                // 将前面返回的cout对象当左值,将'
'移到对象cout,调用函数operator << (char c);
    cout << 1 << endl;          //  end1是换行符常量
    cout << " awsl " << endl;
    
    double a = 0.1;
    double b = 0.2;
    cout << a + b << endl;
    
    return 0;
}
原文地址:https://www.cnblogs.com/zsy12138/p/10832072.html