为什么按位移位(<< 和 >>)用于 cout 和 cin?

2023-10-17C/C++开发问题
2

本文介绍了为什么按位移位(<< 和 >>)用于 cout 和 cin?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

问题确实在标题中;我敢肯定有一些合乎逻辑的,但现在我很难过!

Question is in the title really; I'm sure there is something logical, but for now I'm stumped!

推荐答案

根据C++的设计与演化的§8.3.1:

Doug McIlroy 通过类比 UNIX shell 中的 I/O 重定向操作符(>、>>、| 等)提出了提供输出操作符而不是命名输出函数的想法

The idea of providing an output operator rather than a named output function was suggested by Doug McIlroy by analogy with the I/O redirection operators in the UNIX shell (>, >>, |, etc.)

[...]

输入和输出操作考虑了几个操作符:赋值运算符是输入和输出的候选者,但它以错误的方式绑定.即 cout=a=b 将被解释为 cout=(a=b),并且大多数人似乎更喜欢输入运算符与输出运算符不同.运算符<>都试过了,但是小于"和大于"的含义已经牢牢地植入人们的脑海中,以至于新的I/O语句从所有实际目的来看都是不可读的(<<<>>> 似乎不是这种情况).除此之外,'<'就在大多数键盘上的,"上方,人们写这样的表达方式:

Several operators were considered for input and output operations: the assignment operator was a candidate for both input and output, but it binds the wrong way. That is cout=a=b would be interpreted as cout=(a=b), and most people seemed to prefer the input operator to be different from the output operator. The operators < and > were tried, but the meanings "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 (this does not appear to be the case for << and >>). Apart from that, '<' is just above ',' on most keyboards, and people were writing expressions like this:

cout < x , y, z;

为此提供好的错误消息并不容易.

It is not easy to give good error messages for this.

这篇关于为什么按位移位(&lt;&lt; 和 &gt;&gt;)用于 cout 和 cin?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6