#include<iostream>
using namespace std;
class P
{
private:
double *co;
int n;
public:
P(double a[],int n);
P(){n=0;co=NULL;}
P(const P &b);
~P();
void input(double a[],int n);
P operator+(const P&b)const;
void show()const;
void showco()const;
};
P::P(double a[],int l)
{
n=l;
co=new double[l];
for(int i=0;i<n;i++)
co[i]=a[i];
}
P::P(const P &b)
{
cout<<"copying..from ";
b.show();
n=b.n;
co=new double[n];
for(int i=0;i<n;i++)
co[i]=b.co[i];
}
P::~P()
{
cout<<"Destructing."<<endl;
delete []co;
}
void P::input(double a[],int l)
{
n=l;
co=new double[l];
for(int i=0;i<l;i++)
co[i]=a[i];
}
P P::operator+(const P&b)const
{
int l=n;
double a[l];
for(int i=0;i<l;i++)
a[i]=co[i]+b.co[i];
while(l>=1&&a[l-1]==0)
l--;
//P p(a,l);
//cout<<"return :";p.show();
return P(a,l);
}
void P::show()const
{
if(n==0)
{
cout<<"0\n";
return ;
}
int f=1;
for(int i=0;i<n;i++)
{
if(co[i])
{
if(f)
f=0;
else if(co[i]>0)
cout<<"+";
if(i==0)
cout<<co[i];
else
{
if(co[i]!=1) //系数为1则省略(指数非0)
cout<<co[i];
cout<<"x";
if(i!=1) //指数为1则省略
cout<<"^"<<i;
}
}
}
cout<<endl;
}
void P::showco()const
{
for(int i=0;i<n;i++)
cout<<co[i]<<" ";
cout<<endl;
}
int main()
{
double a[]={1,2,3,4,5,6};
double b[]={2,1,0,-4,-1,-6};
double c[]={-1,-2,-3,-4,-5,-6};
P x(a,6),y,z(c,6);
cout<<"x=";x.show();
cout<<"y=";y.show();
y.input(b,6);
cout<<"y=";y.show();
cout<<"z=";z.show();
P ans=x+y; //用(x+y)为ans初始化,调用复制构造函数
cout<<"ans=x+y=";ans.show(); //无措
ans=x+y; //赋值操作,不调用复制构造函数,将出错,随着(x+y)的消亡,ans中指针无效。
ans.showco();
cout<<"ans=w+y=";ans.show();
ans=y+z; //出错
ans.showco();
cout<<"ans=y+z=";ans.show();
ans=x+z; // 无错
ans.showco();
cout<<"ans=x+z=";ans.show();
}
C++ Polynomial类
最新推荐文章于 2024-04-04 23:42:00 发布