为什么输出运算符'os<<值"而不是“值>>os'? [英] Why is the output operator 'os << value' and not 'value >> os'?

查看:48
本文介绍了为什么输出运算符'os<<值"而不是“值>>os'?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习流媒体.标准流提供<< 运算符,可以将其声明为:

I am learning about streaming. The standard streams provide the << operator which can be declared as:

ostream& operator<<(stream& os, CLASS& rc);  

为什么不可能这样声明它?

Why is it impossible to declare it as this?

ostream& operator>>(CLASS& rc, stream& os); 

那么我也许可以做类似的事情:

Then I may be able to do something like:

rc.something >> os;

作为实施的一部分.

编辑,因为人们帮助我进一步了解了这一点,我很感激.

Edit as people have helped me learn more about this, I am thankful.

但是我仍然坚持如何实现它.

However I am stuck at how to implement actually it.

我尝试过

ostream& operator >> (const SomeClass& refToCls, stream& os)
{
   refToCls.iVar >> os;
   return os;
}

但是失败.我该如何解决?

but it fails. How can I fix it?

推荐答案

事实上,可以定义

ostream& operator>>(CLASS& rc, ostream& os);

但是您必须像这样链接它:

But then you must chain it like this:

a >> (b >> (c >> str));

>> 运算符是左关联的,因此默认情况下是这样的:

The >> operator is left-associative, so by default this:

a >> b >> c >> str;

等效于:

((a >> b) >> c) >> str;

含义错误.

这篇关于为什么输出运算符'os&lt;&lt;值"而不是“值&gt;&gt;os'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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