学了C++的运算符重载,感觉很难懂,做了个简单的+,-,*,+=重载,写出来,加深一下印象。
Description
Develop class Polynomial. The internal representation of a Polynomial is an array of terms. Each term contains a coefficient and an exponent. The term 2*X*X*X*X has the coefficient 2 and the exponent 4. Develop a complete class containing proper constructor and destructor functions as well as set and get functions.
The class should also provide the following overloaded operator capabilities:
a. Overload the addition operator (+) to add two Polynomials.
b. Overload the subtraction operator (-) to subtract two Polynomials.
c. Overload the assignment operator to assign one Polynomial to another.
d. Overload the multiplication operator (*) to multiply two Polynomials.
e. Overload the addition assignment operator (+=).
Input
Enter two integer numbers in a group from the keyboard to initialize the two Polynomial objects.
Output
Print the following result:
a. add two Polynomials objects by addition operator (+), and assign to a new objects
b. Overload the subtraction operator (-) to subtract two Polynomials, and assign to a new objects
c. Overload the multiplication operator (*) to multiply two Polynomials, and assign to a new objects
d. Overload the addition assignment operator (+=), print the left operand.
Sample Input
4 3
Sample Output
674
350
82944
674
Hint
There are 2 groups input in test case.
Source
#include<iostream>
using
namespace std;
class Polynomial
{
public:
Polynomial(int m = 0)
{
setfun(m);
}
~Polynomial()
{
}
void setfun(int a)
{
s = 2*a*a*a*a;
}
int &getfun()
{
return s;
}
private:
int s;
};
Polynomial
operator+(Polynomial sub1,Polynomial sub2)
{
Polynomial sum;
sum.getfun () = sub1.getfun () + sub2.getfun ();
return sum;
}
Polynomial
operator-(Polynomial sub1,Polynomial sub2)
{
Polynomial cha;
cha.getfun () = sub1.getfun () - sub2.getfun ();
return cha;
}
Polynomial
operator*(Polynomial sub1,Polynomial sub2)
{
Polynomial ji;
ji.getfun () = sub1.getfun () * sub2.getfun ();
return ji;
}
Polynomial
operator+=(Polynomial sub1,Polynomial sub2)
{
Polynomial hedeng;
hedeng.getfun () += (sub1.getfun () + sub2.getfun ());
return hedeng;
}
int main()
{
int x,y;
cin>>x;
cin>>y;
Polynomial com1(x),com2(y),total,subduction,product,sumandequ;
total = operator+(com1,com2);
subduction = operator-(com1,com2);
product = operator*(com1,com2);
sumandequ = operator+=(com1,com2);
cout<<total.getfun ()<<"\n"<<subduction.getfun ()<<"\n"<<product.getfun ()
<<"\n"<<sumandequ.getfun ()<<endl;
return 0;
}