``````#include "stdafx.h"
#include<iostream>
using namespace std;
class polynomial{
private:
double sum,*p;
int n;
static int count;
public:
polynomial();
polynomial(const polynomial&a);
~polynomial();
void getpolynomial(int time);
void showcount()const{cout<<"多项式的个数为:"<<count<<endl;}
void display()const;
double compute();
friend polynomial &operator+(const polynomial&b,const polynomial&c);
polynomial &operator-(const polynomial&b);
polynomial &operator*(const polynomial&d);
polynomial&operator=(const polynomial&b);

};
int polynomial::count=0;
polynomial::polynomial():n(0),sum(0),p(0){
count++;
}
polynomial::polynomial(const polynomial&a){
n=a.n;
sum=a.sum;
p=new double[n];
for(int i=0;i<=n;i++)
p[i]=a.p[i];
count++;
}

****polynomial::~polynomial(){
delete[]p;
count--;
//防止内存泄漏
}****

void polynomial::getpolynomial(int time){
n=time;
p=new double[n];//创建动态数组，可以存放任意大小的多项式
for(int i=0;i<=n;i++){
cout<<"输入第"<<i+1<<"项的系数:";
cin>>p[i];}
}
void polynomial::display() const{
for(int i=n;i>=0;i--){
//判断多项式系数是否为0
if(p[i]==0){
cout<<"";
continue;}

//若多项式系数小于0
if(p[i]<0){
if(i==0)
cout<<p[i];
//若次数为1，则不用输出次数项
else if(i==1){
if(p[i]!=-1)
cout<<p[i]<<"x";
else
cout<<"-x";
}
//若系数为-1，则只输出-号
else if(p[i]==-1)
cout<<"-x^"<<i;
//其他情况则按照正常输出
else
cout<<p[i]<<"x^"<<i<<"";
continue;
}
//若多项式系数大于0
if(p[i]>0){
if(i==0)
cout<<"+"<<p[i];
//若次数为1，则不用输出次数项
else if(i==1){
if(p[i]!=1)
cout<<"+"<<p[i]<<"x";
else
cout<<"+x";
}
//若系数为1，则不输出1
else if(p[i]==1)
cout<<"+"<<"x^"<<i;
else
cout<<"+"<<p[i]<<"x^"<<i<<"";
continue;
}

}
cout<<endl;
}
double polynomial::compute(){
double x;
cout<<"\ninput the value of x:";//输入x的值进行计算
cin>>x;
if(x==0)
throw exception();
for(int i=0;i<=n;i++)
sum+=p[i]*(pow(x,i));
cout<<"The result is:"<<sum<<endl;

}

******polynomial& polynomial::operator-(const polynomial&b){
//因为每个多项式系数涉及的是一个固定大小数组，因此需要防止数组下标越界
polynomial temp2;
if(n<=b.n){
temp2.n=b.n;
temp2.p=new double[b.n];
for(int i=0;i<=n;i++)
temp2.p[i]=p[i]-b.p[i];
for(int i=n+1;i<=b.n;i++)
temp2.p[i]=-b.p[i];
}
if(n>b.n){
temp2.n=n;
temp2.p=new double[n];
for(int i=0;i<=b.n;i++)
temp2.p[i]=p[i]-b.p[i];
for(int i=b.n+1;i<=n;i++)
temp2.p[i]=p[i];
}
count--;
return * new polynomial(temp2);
};******
``````

1个回答