当使用cout和cin时,“<<"是什么.和“>"运营商在做什么,我们为什么要使用它们? [英] When using cout and cin, what are the "<<" and ">>" operators doing and why do we use them?

查看:133
本文介绍了当使用cout和cin时,“<<"是什么.和“>"运营商在做什么,我们为什么要使用它们?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

int age;
cin >> age;

cout << "You are " << age << " years old!" << endl;

我们为什么要使用<<"和">>"运算符在这里?他们在做什么?我有点理解位移,但是在这里我不知道它是如何工作的.

Why do we use the "<<" and ">>" operators here? What are they doing? I somewhat understand bit-shifting, but I don't get how that works here.

推荐答案

它们被称为流插入运算符(<<)和流提取运算符(>>).

They are called the stream insertion operator (<<) and the stream extraction operator (>>).

这些运算符与左移和右移运算符相同(即使它们具有不同的名称).位移位运算符是重载的,因此当左侧是流时,它们可以从该流中读取或写入该流.

These are the same operators as the left and right bit shift operators (even though they have different names). The bit shift operators are overloaded, so that when the left side is a stream, they read from or write to that stream.

它们就像任何函数调用一样-它的工作原理是:

They're just like any function call - it works like:

leftShift(leftShift(leftShift(leftShift(cout, "You are "), age), " years old!"), endl);

该函数被称为operator<<而不是leftShift.
严格来说,没有理由称leftShift为左移函数,同样也没有理由称operator<<为左移函数.

except that the function is called operator<< instead of leftShift.
Strictly speaking, there's no reason that a function called leftShift has to do a left shift, and likewise there's no reason a function called operator<< has to do a left shift.

这篇关于当使用cout和cin时,“&lt;&lt;"是什么.和“&gt;"运营商在做什么,我们为什么要使用它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆