自定义输入输出流的那些事儿
2016-04-12 23:25
267 查看
今天,帮同学调了调代码,发现网上关于自定义输出输入流的问题太少了,以下就我同学的代码简单的谈一谈吧~
以下是我同学的错误代码:
error:ambiguous overload for 'operater>>' in 'is>>d.point::x'
以下是这份代码有问题的几个地方:
1.友元(friend)不需要定义inline类型;
2.point前不需要const定义;
3.友元定义的输入输出流模板有误:
应该为:friend ostream & operator<<(ostream &;point &);
friend istream & operator>>(istream &;point &);
4.问题最大的还是cout<<s+t;
这段代码直接违背了自己写的自定义输出流。
应该改为:
point c;
c=s+t;
cout<<c;
以下是改正后的代码:
以下是跑出来的结果:
希望能够帮助大家!
以下是我同学的错误代码:
#include<iostream> using namespace std; class point{ int x,y; public: void set(int a,int b){x=a;y=b;} point operator+(const point&d) { point s; s.set(x+d.x,y+d.y); return s; } friend ostream & operator<<(ostream & o,const point&d); friend istream & operator>>(istream & is,const point&d); }; inline ostream&operator<<(ostream & o,const point&d) { return o<<"("<<d.x<<","<<d.y<<")"<<endl;; } inline istream&operator>>(istream & is,const point&d) { return is>>d.x>>d,y; } int main() { point s,t; cout<<"please enter two numbers"<<endl; cin>>s; cout<<"please enter another two numbers"<<endl; cin>>t; cout<<"the total is"<<" "; cout<<s+t; return 0; }我用的IDE是code::blocks,报错信息为:
error:ambiguous overload for 'operater>>' in 'is>>d.point::x'
以下是这份代码有问题的几个地方:
1.友元(friend)不需要定义inline类型;
2.point前不需要const定义;
3.友元定义的输入输出流模板有误:
应该为:friend ostream & operator<<(ostream &;point &);
friend istream & operator>>(istream &;point &);
4.问题最大的还是cout<<s+t;
这段代码直接违背了自己写的自定义输出流。
应该改为:
point c;
c=s+t;
cout<<c;
以下是改正后的代码:
#include<iostream> using namespace std; class point{ int x,y; public: void set(int a,int b){x=a;y=b;} point operator+(point&d) { point s; s.set(x+d.x,y+d.y); return s; } friend ostream & operator<<(ostream & , point&); friend istream & operator>>(istream & , point&); }; ostream&operator<<(ostream & o, point&d) { return o<<"("<<d.x<<","<<d.y<<")"<<endl; } istream&operator>>(istream & is, point&d) { return is>>d.x>>d.y; } int main() { point s,t,c; cout<<"please enter two numbers"<<endl; cin>>s; cout<<"please enter another two numbers"<<endl; cin>>t; cout<<"the total is"<<" "; c=s+t; cout<<c; return 0; }
以下是跑出来的结果:
希望能够帮助大家!
相关文章推荐
- 集群搭建
- No configuration found for the specified action: 'login123.action' in namespace: '/'.
- 用 Redis 轻松实现秒杀系统---双十一和12306的瞬时网络爆发访问
- LeetCode 206. Reverse Linked List
- ARM-指令
- android去掉黑色状态栏
- CSUST 第九届校赛G-Dating with girls(二分)
- Android笔记【2】--View
- 数据库学习感悟
- 数据结构——线段树的基础知识
- Spark常用函数讲解--键值RDD转换
- c++作业3:项目2到项目四
- Hadoop配置
- 文件系统vs对象存储——选型和趋势
- Objective-C中NSArray和NSMutableArray的基本用法
- c++实验3
- Cocos2.2.6创建项目cd tools/project-creator/
- 第三百七十五天 how can I 坚持
- 大牛工程师要知道的PCB技巧100问
- PLSQL安装:ORA-12154:TNS:无法解析指定的连接符