今天,帮同学调了调代码,发现网上关于自定义输出输入流的问题太少了,以下就我同学的代码简单的谈一谈吧~
以下是我同学的错误代码:
#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;
}
以下是跑出来的结果:
希望能够帮助大家!