前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >运算符重载流输入输出<< >>

运算符重载流输入输出<< >>

作者头像
我与梦想有个约会
发布2023-10-20 16:23:08
1190
发布2023-10-20 16:23:08
举报
文章被收录于专栏:jiajia_dengjiajia_deng

流输入输出运算符 >> << 比较简单,C++提供了固定的格式,语法上并不是非常难,你只需要记住 istream 和 ostream 这两个类就可以了。本文使用了友元函数方式来实现。具体实现的代码如下,请注意看返回 istream 和 ostream 引用的原因是为了可以使用连续的>>或<<操作符来输入输出。

代码语言:javascript
复制
#include 
using namespace std;
class Complex
{
public:
Complex(float x = 0, float y = 0)
:_x(x), _y(y) {}
friend istream& operator>>(istream& is, Complex& another);
friend ostream& operator<<(ostream& os, Complex& another);
private:
float _x;
float _y;
};
istream& operator>>(istream& is, Complex& another)
{
is >> another._x >> another._y;
return is;
}
ostream& operator<<(ostream& os, Complex& another)
{
os << another._x << “ “ <<  another._y << endl;
return os;
}
int main(int argc, char* argv[])
{
Complex c, c2;
// 考虑连等的情况,实现函数要返回 istream 对象的引用
cin >> c >> c2;
cout << c << c2;
return 0;
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2015-05-21,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档