为啥 iostream 选择重载 \u003c\u003c 和 \u003e\u003e 操作符进行输入和输出操作

《C++ 语言的设计与演化》第 8.3.1 节 I/O流库中有提到过,用 \u0026gt;\u0026gt; 和 \u0026lt;\u0026lt; 来输入输出是由 Doug McIlroy 爷爷提出来的,为的是模仿 Unix shell 的 IO 重定向:写内容到文件:echo "Hello, World!" \u0026gt;\u0026gt; output.txt从文件读内容:sendmail -f user@example.com \u0026lt;\u0026lt; content.txtStroustrup 爷爷在《C++ 编程设计语言》里提到:But why \u0026lt;\u0026lt;? It is not possible to invent a new lexical token . The assignment operator was a candidate for both input and output, but most people seemed to prefer to use different operators for input and output. Furthermore, = binds the wrong way; that is, cout=a=b means cout=(a=b) rather than (cout=a)=b . I tried the operators \u0026lt; and \u0026gt;, but the mean ‘‘less than’’ and ‘‘greater than’’ were so firmly implanted in people’s minds that the new I/O statements were for all practical purposes unreadable.歌词大意:为什么选 \u0026lt;\u0026lt; 呢?首先,你不可能仅仅为这个操作就去发明一个新的符号;用赋值运算符的话,输入输出就得用相同的运算符,而且 cout=a=b 也会被编译器误解为 cout=(a=b);用 \u0026gt; 和 \u0026lt; 吧,大于和小于的意义又根深蒂固,于代码的可读性无益。
■网友
我感觉 C++ 利用了 C 的一个历史遗留设计缺陷:左移/右移运算符优先级比 +、- 等还低。为什么这么说呢?因为左移相当于 *2,右移相当于 /2,所以原本应当跟 * / 是同一个优先级才更自然啊……
■网友
你看\u0026lt;\u0026lt;和\u0026gt;\u0026gt;是不是长得像箭头?而通常用箭头表示方向时是指向尖的那端,所以cout\u0026lt;\u0026lt;var表示数据从变量流向输出流,自然就是输出了,cin\u0026gt;\u0026gt;var表示数据从输入流流向变量,自然就是输入了
■网友
山寨shell的输入输出重定向。


    推荐阅读