要求:
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();
}
将上述多项式类(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中的+,-,*,+=这四个成员函数改为友元函数,采用同样的主函数验证