Why are bitwise shifts (<< and>>) used for cout and cin?

后端 未结 13 1697
眼角桃花
眼角桃花 2020-12-02 16:16

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

13条回答
  •  旧巷少年郎
    2020-12-02 17:15

    From "The C++ Programming language". Stroustrup's(language authors) words:

    Overloading the operator << to mean ‘‘put to’’ gives a better notation and lets the programmer output a sequence of objects in a single statement.

    But why <<? 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 < and >, 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.

提交回复
热议问题