自定义输入输出流的那些事儿

  今天,帮同学调了调代码,发现网上关于自定义输出输入流的问题太少了,以下就我同学的代码简单的谈一谈吧~

以下是我同学的错误代码:

#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;
}

以下是跑出来的结果:



希望能够帮助大家!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值