多项式类的构造

class polynomial
{
    int *a;
    int power;
public:
    polynomial(int n)
    {
        power = n;
        a = new int[n+1];
        for(int i=0;i<=n;i++)
        {
            a[i] = 0;
        }
    }
    polynomial(int aa[], int n)
    {
        power = n;
        a = new int[n+1];
        for(int i=0;i<=n;i++)
        {
            a[i] = aa[i];
        }
    }
    polynomial(const polynomial &p)
    {
        power = p.power;
        a = new int[power];
        for(int i=0;i<=power;i++)
        {
            a[i] = p.a[i];
        } 
    }
    ~polynomial()
    {
        delete []a;
    }
    void show()
    {
        for(int i=0;i<=power;i++)
        {
            if(i==0)
            {
                cout<<a[i]<<"+";
            }
            else if(i==power)
            {
                cout<<a[i]<<"x^"<<i;
            }
            else
            {
                cout<<a[i]<<"x^"<<i<<"+";
            }
        }
        cout<<endl;
    }
    polynomial operator+(const polynomial &p)
    {
        polynomial p0(power>p.power?power:p.power);
        if(power>p.power)
        {
            for(int i=0;i<=p.power;i++)
            {
                p0.a[i] = a[i] + p.a[i];
            }
            for(int i=p.power+1;i<=power;i++)
            {
                p0.a[i] = a[i];
            }

        }
        else
        {
            for(int i=0;i<=power;i++)
            {
                p0.a[i] = a[i] + p.a[i];
            }
            for(int i=power+1;i<=p.power;i++)
            {
                p0.a[i] = p.a[i];
            }
        }
        return p0;
    }
    
};

int main()
{
    int a[] = {1,3,5,7,5,5};
    polynomial p1(a,5);
    p1.show();
    polynomial p2(p1);
    p2.show();
    int b[] = {4,6,6};
    polynomial p3(b,2);
    p3.show();
    polynomial p4 = p3+p2;
    p4.show();
}  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值