它的意义是将整数1按位左移2位,即:
重载左移操作符,将变量或者常量左移到一个对象中
代码示例:
- #include <stdio.h>
- const char endl = '\n';
- class Console
- {
- public:
- Console& operator <<(int i)
- {
- printf("%d\n",i);
- return *this;
- }
- Console& operator << (char c)
- {
- printf("%c\n",c);
- return *this;
- }
- Console& operator <<(const char* s)
- {
- printf("%s\n",s);
- return *this;
- }
- Console& operator << (double d)
- {
- printf("%f\n",d);
- return *this;
- }
- };
- Console cout;
- int main()
- {
- cout<<1 << endl;
- cout<<"TXP"<<endl;
- double a = 0.1;
- double b = 0.2;
- cout << a + b <<endl;
- return 0;
- }
运行结果:
- root@txp-virtual-machine:/home/txp# ./a.out
- 1
- TXP
- 0.300000
从上面我们可以看到,不直接使用printf函数去打印这个值,这个以前在书上,都是直接讲解把数值说送到输出流中去,但是你一开始学习cout函数(或者说你还没有接触到对象的时候,根本不明白这什么意思);如果进行了左移的重载之后,那么程序将产生神奇的变化,所以在 main() 中不用 printf() 和格式化字符串 '\n' 了,因为编译器会通过重载的机制会为我们选择究竟使用哪一个重载机制。
|