```
//
// 12288
// : 424103019
//Question 2
//Polynomial.cpp
enum Error_code {success,fail};
class Polynomial {
public:
Polynomial(int = 10);
Polynomial(const Polynomial &);
Polynomial operator+(const Polynomial &);
Polynomial operator-(const Polynomial &);
Polynomial operator*(const Polynomial &);
Polynomial &operator=(const Polynomial &);
Polynomial &operator+=(const Polynomial &);
Polynomial &operator-=(const Polynomial &);
Polynomial &set(int=0,double=0);
void print()const;
double Get(int =0);
~Polynomial();
private :
double *a;
int grade;
};
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
Polynomial::Polynomial(int s)
{
grade = (s>0 && s<1000 ? s : 10);
a = new double[grade+1];
for(int i=0;i<=grade;i++)
a[i] = 0;
}
Polynomial::Polynomial(const Polynomial &x)
{
grade = x.grade;
a = new double [grade+1];
for(int i=0;i<=grade;i++)
a[i] = x.a[i];
}
Polynomial &Polynomial::operator =(const Polynomial &x)
{
if (this != &x)
{
if (grade != x.grade) {
grade = x.grade;
delete a;
a = new double [grade+1];
}
for(int i=0;i<=grade;i++)
a[i] = x.a[i];
}
return *this;
}
Polynomial Polynomial::operator +(const Polynomial &x)
{
int s = grade >= x.grade ? grade : x.grade;
Polynomial temp(s);
for(int i=0;i<=x.grade;i++)
temp.a[i] += x.a[i];
for(int j=0;j<=grade;j++)
temp.a[j] += a[j];
return temp;
}
Polynomial Polynomial::operator-(const Polynomial &x)
{
int i=0,j;
int s = grade >= x.grade ? grade : x.grade;
if ((x.grade == grade) && (a[grade]-x.a[x.grade]==0) ) {s--;i = 1;}
Polynomial temp(s);
for(j=i;j<=grade;j++)
temp.a[j-i] += a[j];
for(j=i;j<=x.grade;j++)
temp.a[j-i] -= x.a[j];
return temp;
}
Polynomial &Polynomial::operator +=(const Polynomial &x)
{
*this = *this +x;
return *this;
}
Polynomial &Polynomial::operator -=(const Polynomial &x)
{
*this = *this - x;
return *this;
}
Polynomial &Polynomial::set(int exp,double coff)
{
if (exp >=0 && exp<=grade) {
a[exp] = coff;
}
return *this;
}
Polynomial Polynomial::operator*(const Polynomial &x)
{
int s = grade + x.grade,i,j;
Polynomial temp(s);
for(i=0;i<=grade;i++)
for(j=0;j<=x.grade;j++)
temp.a[i+j]+=(a[i]*x.a[j]);
return temp;
}
void Polynomial::print()const {
for(int i=grade;i>=0;i--)
cout << (i!= grade && a[i]>=0 ? '+' : ' ' )
<< a[i] << "x^" << i;
cout << endl;
}
double Polynomial::Get(int exp)
{
if (exp >= 0 && exp<=grade)
return a[exp];
return 0;
}
Polynomial::~Polynomial()
{
delete []a;
}
int main()
{
Polynomial A(2),B(5),C;
A.set(2,4).set(1,-5).set(0,6);
B.set(5,1).set(4,4).set(3,3).set(2,-2).set(0,16);
cout << "A = ";
A.print();
cout << "B = ";
B.print();
C = A+B;
cout << "C = A+B : ";
C.print();
C = A-B;
cout << "C = A-B : ";
C.print();
C = B-A;
cout << "C = B-A : ";
C.print();
C = B*A;
cout << "C = A*B : ";
C.print();
C += B;
cout << "C += B : ";
C.print();
C -=A;
cout << "C -= A : ";
C.print();
cout << "The coffecient of exp 0 in B is :" << B.Get(0) << endl;
return 0;
}
```