我在重载 + 运算符时遇到问题,我无法弄清楚原因是什么。+ 运算符返回一个多项式(称为 C),但它按值返回它,其中赋值运算符期望一个多项式对象作为通过引用传递的参数。为了使 C=A+B 工作,我是否需要第二个赋值运算符函数,它将按值传递的多项式作为参数?谢谢!
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
void line(int lines);
class Polynomial
{
private:
int degree;
int* coeffs;
public:
//constructors
Polynomial() {degree=0;coeffs=new int[1];}
Polynomial(int deg) {degree=deg;coeffs=new int[deg+1];}
Polynomial(const Polynomial& A);
//mutators
void GetCoeffs(istream& in);
void EditCoeff(int deg);
void ResetCoeffs();
int Coeff(int deg);
void Randomize(int max);
//accessors
void Show(ostream& out);
int Degree() {return degree;}
//operators
friend Polynomial operator+(Polynomial& A, Polynomial& B);
void operator =(Polynomial A);
};
int main()
{
Polynomial A(5);
Polynomial B(5);
A.Randomize(5);
B.Randomize(5);
A.Show(cout);
line(2);
B.Show(cout);
line(2);
Polynomial C(5);
C=A+B;
C.Show(cout);
return 0;
}
void Polynomial::Randomize(int max)
{
for (int i=degree; i>=0; i--)
{
coeffs[i]=rand()%(max+1) + 1;
if ((rand()%(101) + 1)%2 == 0)
coeffs[i]*=-1;
}
}
void Polynomial::operator =(Polynomial A)
{
if (degree==A.degree)
{
for (int i=degree; i>=0; i--)
{
coeffs[i]=A.coeffs[i];
}
}
}
Polynomial Polynomial::operator+(Polynomial& A, Polynomial& B)
{
Polynomial C;
if (A.degree>=B.degree)
{
C=A;
for (int i=B.degree; i>=0; i--)
{
C.coeffs[i]=A.coeffs[i]+B.coeffs[i];
}
C.Show(cout);
return C;
}
else
{
C=B;
for (int i=A.degree; i>=0; i--)
{
C.coeffs[i]=A.coeffs[i]+B.coeffs[i];
}
C.Show(cout);
return C;
}
}
int Polynomial::Coeff(int deg)
{
return coeffs[deg];
}
void line(int lines)
{
for (int i=0; i<lines; i++)
cout << endl;
}
void Polynomial::GetCoeffs(istream& in)
{
for (int i=degree; i>=0; i--)
{
in >> coeffs[i];
}
in.ignore();
}
void Polynomial::Show(ostream& out)
{
for (int i=degree; i>=0; i--)
{
if (coeffs[i]>=0)
{
if (i!=degree)
out << " + ";
out << coeffs[i];
}
else
{
if (coeffs[i]<0)
out << " - ";
out << 0-coeffs[i];
}
if (i>1)
out << "x^" << i;
else if (i==1)
out << "x";
}
}
Polynomial::Polynomial(const Polynomial& A)
{
coeffs=new int[A.degree+1];
degree=A.degree;
for (int i=A.degree; i>=0; i--)
{
coeffs[i]=A.coeffs[i];
}
}