C++建立多项式类并实现相关操作

  1. 建立一个多项式类(CPoly),多项式类的数据成员包括最高幂次,各项系数,操作包括加法、减法、乘法、显示和输入。多项式类的定义如下: class CPoly { private: int degree; //最高项次数 double coef[10]; //各项系数 public: CPoly(double, double); //构造一次多项式 CPoly(double, double, double); //构造二次多项式 CPoly(CPoly&); //复制构造函数 CPoly Add(CPoly&); //多项式加 CPoly Sub(CPoly&); //多项式减 CPoly Mul(CPoly&); //多项式乘 void Print(); //打印多项式 };

要求:
1) 完成上述成员函数并用如下主函数完成检验,可补充必要的其他成员函数。
2) 打印多项式时用X^n表示各幂次项(n>1),形如-5*X^4+3*X^2-2*X+3。系数为0的项不打印;系数<0的项如-2*X打印为3*X^3-2*X而不是3*X^3+-2*X。

void main()
{
srand((int)time(0));
CPoly p1((rand()%10)-5, (rand()%10)-5), p2=p1;
CPoly p3((rand()%10)-5, (rand()%10)-5, (rand()%10)-5);
CPoly tp1, tp2, tp3;

cout<<"p1 = "; p1.Print();
cout<<"p2 = "; p2.Print();
cout<<"p3 = "; p3.Print();

cout<<endl;
tp1=p1.Add(p2);
cout<<"tp1 = p1+p2 = "; tp1.Print(); 
cout<<"p1 = "; p1.Print(); 
cout<<"p2 = "; p2.Print(); 

cout<<endl;
tp2=tp1.Sub(p3);
cout<<"tp2 = tp1-p3 = "; tp2.Print();
cout<<"tp1 = "; tp1.Print(); 
cout<<"p3 = "; p3.Print(); 

cout<<endl;
tp3=tp1.Mul(tp2);
cout<<"tp3 = tp1*tp2 = "; tp3.Print();
cout<<"tp1 = "; tp1.Print(); 
cout<<"tp2 = "; tp2.Print();

}

  1. 将上述多项式类(CPoly)中实现多项式操作的成员函数改为操作符重载函数,采用如下主函数验证
    void main()
    {
    srand((int)time(0));
    CPoly p1((rand()%10)-5, (rand()%10)-5), p2;
    CPoly p3((rand()%10)-5, (rand()%10)-5, (rand()%10)-5);
    CPoly tp1, tp2, tp3, tp4;

    p2=p1;
    cout<<"p1 = "; p1.Print();
    cout<<"p2 = "; p2.Print();
    cout<<"p3 = "; p3.Print();

    cout<<endl;
    tp1=p1+p2;
    cout<<"tp1 = p1+p2 = "; tp1.Print();
    cout<<"p1 = "; p1.Print();
    cout<<"p2 = "; p2.Print();

    cout<<endl;
    tp2=tp1-p3;
    cout<<"tp2 = tp1-p3 = "; tp2.Print();
    cout<<"tp1 = "; tp1.Print();
    cout<<"p3 = "; p3.Print();

    cout<<endl;
    tp4=tp3=tp1*tp2;
    cout<<"tp3 = tp1*tp2 = "; tp3.Print();
    cout<<"tp4 = tp3 = "; tp4.Print();
    cout<<"tp1 = "; tp1.Print();
    cout<<"tp2 = "; tp2.Print();

    cout<<endl;
    tp4=tp1+=tp3;
    cout<<"tp1 += tp3 = "; tp1.Print();
    cout<<"tp4 = tp1 = "; tp4.Print();
    cout<<"tp3 = "; tp3.Print();
    }

  2. 将习题2中的+,-,*,+=这四个成员函数改为友元函数,采用同样的主函数验证

不知道你这个问题是否已经解决, 如果还没有解决的话:

如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^