返回类型在流运算符重载 [英] return type in stream operator overloading

查看:224
本文介绍了返回类型在流运算符重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

程序的目的是接受输入,将这些值赋给类的成员并显示输出,输入和输出操作是通过重载流操作符来完成的。

The purpose of program is to take input, assign those values to the members of the class and display the output, with the input and output operation being done by overloading stream operators.

#include <iostream>
using namespace std;
class MyClass {
int x, y;
public:
  MyClass(int i, int j) { 
     x = i; 
     y = j; 
  }

  friend ostream& operator<<(ostream &stream, MyClass ob);
  friend istream& operator>>(istream &stream, MyClass &ob);
 // friend void operator<<(ostream &stream, MyClass ob);
 // friend void operator>>(istream &stream, MyClass &ob);
};

ostream& operator<<(ostream &stream, MyClass ob)
{
  stream << ob.x << ' ' << ob.y << '\n';

  return stream;
}

istream& operator>>(istream &stream, MyClass &ob)
{
  stream >> ob.x >> ob.y;

   return stream;
}

int main()
{
MyClass abt(30,23);
cin>>abt;
cout<<abt;
return 0;
}

在示例中,如果数据是从输入流cin值被分配在函数内部,为什么'istream'返回。我已经看到所有的教程返回流在操作符重载函数。返回值的目的是什么?

In the example, if data is taken from input stream 'cin' and the values are assigned inside the function, why should 'istream' be returned back. I have seen all tutorials return stream in operator overloading function. What is the purpose of return value?

推荐答案


cin ,并且在函数内部赋值,为什么应该返回 istream

In the example, if data is taken from input stream cin and the values are assigned inside the function, why should istream be returned back?

这样做是为了允许链接。

This is done to allow "chaining".

运算符从>> 的两侧获取其两个参数。流来自左边,变量来自右边。当你这样做

The operator takes its two parameters from both sides of >>. The stream comes from the left, and the variable comes from the right. When you do this

cin >> x >> y;

第一个表达式 cin> x 在第二个表达式的左边,这意味着 cin>>> x 变为 ...>> y 的输入流。这就是为什么操作员需要返回传入它的相同输入流。

the first expression cin >> x is on the left of the second expression, which means that the result of cin >> x becomes ... >> y's input stream. That is why the operator needs to return the same input stream that has been passed into it.

这篇关于返回类型在流运算符重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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