#include<iostream>
using namespace std;
class term
{
public:
int exp;
int coeff;
};
class poly
{
public:
term* term_ptr;
int no_term;
poly(int d);
friend istream& operator>>(istream& in, poly& p);
friend ostream& operator<<(ostream& out, const poly& p);
friend poly operator+(const poly& p1, const poly& p2);
};
poly::poly(int d=0)
{
no_term = d;
term_ptr = new term[no_term];
}
istream& operator>>(istream& in, poly& p)
{
in>>p.no_term;
for(int i= 0; i<p.no_term; i++)
{
in>>(p.term_ptr+i)->coeff;
in>>(p.term_ptr+i)->exp;
}
return in;
}
我重载了输入运算符来输入对象。我面临的问题是当我输入两个对象时,第一个对象输入的数据成员随之发生变化。
int main(void)
{
poly p1, p2;
cin>>p1;
cin>>p2;
cout<<p1;
cout<<p2;
return 0;
}
如果输入是
3
1 1
1 2
1 3
3
1 1
1 2
1 3
我得到的输出是
1 1
1 2
1 1
1 1
1 2
1 3
输出算子函数是
ostream& operator<<(ostream& out, const poly& p)
{
out<<"coeff"<<" "<<"power"<<endl;
for(int i = 0; i< p.no_term; i++)
out<<(p.term_ptr+i)->coeff<<" "<<(p.term_ptr+i)->exp<<endl;
return out;
}