#include "stdafx.h"
#include <iostream>
#include<list>
#include<assert.h>
using namespace std;
class Term{ //代表多项式中的每一项
friend ostream& operator<<(ostream&, Term&);
friend istream& operator>>(istream&, Term&);
friend class Polynominal;
public:
Term(int c,int e) : coef(c), exp(e){}
Term& operator+(Term&);
private:
int coef;
int exp;
};
ostream& operator<<(ostream& out, Term& t){//输出单项
if(t.coef==0) return out;
else if(t.coef>0) out<<"+";
out<<t.coef<<"x^"<<t.exp;
return out;
}
istream& operator>>(istream& in, Term& t){//输入单项,包括指数和系数
cout<<"Input coef & exp: "<<endl;
in>>t.coef>>t.exp;
return in;
}
Term& Term::operator +(Term& t){//项与项的加法
assert(exp==t.exp);
Term* term=term=new Term(coef+t.coef, exp);
return *term;
}
/********************************************************************
********************************************************************/
class Polynominal{//多项式,用一个链表存储
friend istream& operator>>(istream&, Polynominal&);
friend ostream& operator<<(ostream&, Polynominal&);
public:
Polynominal& operator+(Polynominal&);
private:
list<Term> pList;
};
istream& operator>>(istream& in, Polynominal& poly){//输入Polynominal
int n=0;
cout<<"Input NUM of Term: "<<endl;
cin>>n;
cout<<"Input Every Term of The Polynominal: "<<endl;
Term t(0,0);
for(int i=0;i<n;i++){
cin>>t;
poly.pList.push_back(t);
}
return in;
}
template <class T>
ostream& operator<<(ostream& out, list<T>& myList){//重载实现对list的输出
list<T>::iterator iter;
for(iter=myList.begin();iter!=myList.end();iter++)
cout<<*iter<<" ";
cout<<endl;
return out;
}
ostream& operator<<(ostream& out, Polynominal& poly){//输出Polynominal
out<<poly.pList;
return out;
}