C++大学教程(第七版)课后习题答案第十十一章

857 阅读3分钟

第十章

10.7(重载括号运算符)

//DoubleSubscriptedArray.h
#ifndef DOUBLE_SUBSCRIPTED_ARRAY_H
#define DOUBLE_SUBSCRIPTED_ARRAY_H

#include <iostream>
using namespace std;

class DoubleSubscriptedArray
{
   friend ostream &operator<<(
      ostream &, const DoubleSubscriptedArray & );
   friend istream &operator>>( istream &, DoubleSubscriptedArray & );
public:
   DoubleSubscriptedArray( int = 3, int = 3 );
   DoubleSubscriptedArray( const DoubleSubscriptedArray & );
   ~DoubleSubscriptedArray();
   int getRowSize() const;
   int getColumnSize() const;
   const DoubleSubscriptedArray &operator=(
      const DoubleSubscriptedArray & );
   bool operator==( const DoubleSubscriptedArray & ) const;
   bool operator!=( const DoubleSubscriptedArray &right ) const
   {
      return !( *this == right );
   }
   int &operator()( int, int );
   int operator()( int, int ) const;
private:
   int rowSize;
   int columnSize;
   int *ptr;
};

#endif
//DoubleSubscriptedArray.cpp
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include "DoubleSubscriptedArray.h"
using namespace std;

DoubleSubscriptedArray::DoubleSubscriptedArray(
    int rowSizeEntered, int columnSizeEntered)
{
    rowSize = (rowSizeEntered > 0 ? rowSizeEntered : 3);
    columnSize = (columnSizeEntered > 0 ? columnSizeEntered : 3);
    ptr = new int[rowSize * columnSize];
    for (int loop = 0; loop < rowSize * columnSize; loop++)
        ptr[loop] = 0;
}

DoubleSubscriptedArray::DoubleSubscriptedArray(
    const DoubleSubscriptedArray& arrayToCopy)
    : rowSize(arrayToCopy.rowSize), columnSize(arrayToCopy.columnSize)
{
    ptr = new int[rowSize * columnSize];
    for (int loop = 0; loop < rowSize * columnSize; loop++)
        ptr[loop] = arrayToCopy.ptr[loop];
}

DoubleSubscriptedArray::~DoubleSubscriptedArray()
{
   delete [] ptr;
}

int DoubleSubscriptedArray::getRowSize() const
{
   return rowSize;
}

int DoubleSubscriptedArray::getColumnSize() const
{
   return columnSize;
}

const DoubleSubscriptedArray& DoubleSubscriptedArray::operator=(
    const DoubleSubscriptedArray& right)
{
    if (&right != this)
    {
        if (rowSize * columnSize != right.rowSize * right.columnSize)
        {
            delete[] ptr;
            rowSize = right.rowSize;
            columnSize = right.columnSize;
            ptr = new int[rowSize * columnSize];
        }
        for (int loop = 0; loop < rowSize * columnSize; loop++)
            ptr[loop] = right.ptr[loop];
    }
    return *this;
}

bool DoubleSubscriptedArray::operator==(
    const DoubleSubscriptedArray& right) const
{
    if (rowSize * columnSize != right.rowSize * right.columnSize)
        return false;
    for (int loop = 0; loop < rowSize * columnSize; loop++)
        if (ptr[loop] != right.ptr[loop])
            return false;
    return true;
}

int& DoubleSubscriptedArray::operator()(
    int rowSubscript, int columnSubscript)
{
    if ((rowSubscript < 0 || rowSubscript >= rowSize) ||
        (columnSubscript < 0 || columnSubscript >= columnSize))
    {
        cerr << "\nError: One or both subscripts out of range" << endl;
        exit(1);
    }
    return ptr[(rowSubscript * columnSize) + columnSubscript];
}

int DoubleSubscriptedArray::operator()(
    int rowSubscript, int columnSubscript) const
{
    if ((rowSubscript < 0 || rowSubscript >= rowSize) ||
        (columnSubscript < 0 || columnSubscript >= columnSize))
    {
        cerr << "\nError: One or both subscripts out of range" << endl;
        exit(1);
    }
    return ptr[(rowSubscript * columnSize) + columnSubscript];
}

istream &operator>>( istream &input, DoubleSubscriptedArray &a )
{
   for ( int loop = 0; loop < a.rowSize * a.columnSize; loop++ )
      input >> a.ptr[ loop ];
   return input;
}

ostream &operator<<( ostream &output, const DoubleSubscriptedArray &a )
{
   for ( int loop = 0; loop < a.rowSize; loop++ )
   {
      for ( int loop2 = 0; loop2 < a.columnSize; loop2++ )
         output << a.ptr[ ( loop * a.columnSize ) + loop2 ] << ' ';
      output << endl;
   }
   return output;
}
//main.cpp
#include <iostream>
#include "DoubleSubscriptedArray.h"
using namespace std;

int main()
{
    DoubleSubscriptedArray integers1(2, 4);
    DoubleSubscriptedArray integers2;
    cout << "Size of DoubleSubscriptedArray integers1 is "
        << integers1.getRowSize() << " X " << integers1.getColumnSize()
        << "\nDoubleSubscriptedArray after initialization:\n" << integers1;
    cout << "\nSize of DoubleSubscriptedArray integers2 is "
        << integers2.getRowSize() << " X " << integers2.getColumnSize()
        << "\nDoubleSubscriptedArray after initialization:\n" << integers2;
    cout << "\nEnter 17 integers:" << endl;
    cin >> integers1 >> integers2;
    cout << "\nAfter input, the DoubleSubscriptedArrays contain:\n"
        << "integers1:\n" << integers1
        << "\nintegers2:\n" << integers2 << endl;
    cout << "Evaluating: integers1 != integers2" << endl;
    if (integers1 != integers2)
        cout << "integers1 and integers2 are not equal" << endl;
    DoubleSubscriptedArray integers3(integers1);
    cout << "\nSize of DoubleSubscriptedArray integers3 is "
        << integers3.getRowSize() << " X " << integers3.getColumnSize()
        << "\nDoubleSubscriptedArray after initialization:\n" << integers3;
    cout << "\nAssigning integers2 to integers1:" << endl;
    integers1 = integers2;
    cout << "integers1:\n" << integers1
        << "\nintegers2:\n" << integers2;
    cout << "\nEvaluating: integers1 == integers2" << endl;
    if (integers1 == integers2)
        cout << "integers1 and integers2 are equal" << endl;
    cout << "\nintegers1( 1, 2 ) is " << integers1(1, 2);
    cout << "\n\nAssigning 1000 to integers1( 1, 2 )" << endl;
    integers1(1, 2) = 1000;
    cout << "integers1:\n" << integers1;
    cout << "\nAttempt to assign 1000 to integers1( 15, 2 )" << endl;
    integers1(15, 2) = 1000;
}

10.8(Complex类)

//Complex.h
#ifndef COMPLEX_H
#define COMPLEX_H

#include <iostream>
using namespace std;

class Complex
{
   friend ostream &operator<<( ostream &, const Complex & );
   friend istream &operator>>( istream &, Complex & );
public:
   Complex( double = 0.0, double = 0.0 );
   Complex operator+( const Complex& ) const;
   Complex operator-( const Complex& ) const;
   Complex operator*( const Complex& ) const;
   Complex& operator=( const Complex& );
   bool operator==( const Complex& ) const;
   bool operator!=( const Complex& ) const;
private:
   double real;
   double imaginary;
};

#endif
//Complex.cpp
#include <iostream>
#include "Complex.h"
using namespace std;

Complex::Complex( double realPart, double imaginaryPart )
   : real( realPart ),
   imaginary( imaginaryPart )
{
}

Complex Complex::operator+( const Complex &operand2 ) const
{
   return Complex( real + operand2.real,
      imaginary + operand2.imaginary );
}

Complex Complex::operator-( const Complex &operand2 ) const
{
   return Complex( real - operand2.real,
      imaginary - operand2.imaginary );
}

Complex Complex::operator*( const Complex &operand2 ) const
{
   return Complex(
      ( real * operand2.real ) + ( imaginary * operand2.imaginary ),
      ( real * operand2.imaginary ) + ( imaginary * operand2.real ) );
}

Complex& Complex::operator=( const Complex &right )
{
   real = right.real;
   imaginary = right.imaginary;
   return *this;
}

bool Complex::operator==( const Complex &right ) const
{ 
   return ( right.real == real ) && ( right.imaginary == imaginary );
}

bool Complex::operator!=( const Complex &right ) const
{
   return !( *this == right ); 
}

ostream& operator<<( ostream &output, const Complex &complex )
{
   output << "(" << complex.real << ", " << complex.imaginary << ")";
   return output;
}

istream& operator>>( istream &input, Complex &complex )
{
   input.ignore();
   input >> complex.real;
   input.ignore( 2 );
   input >> complex.imaginary;
   input.ignore();
   return input;
}
//main.cpp
#include <iostream>
#include "Complex.h"
using namespace std;

int main()
{
   Complex x, y( 4.3, 8.2 ), z( 3.3, 1.1 ), k;
   cout << "Enter a complex number in the form: (a, b)\n? ";
   cin >> k;
   cout << "x: " << x << "\ny: " << y << "\nz: " << z << "\nk: "
      << k << '\n';
   x = y + z;
   cout << "\nx = y + z:\n" << x << " = " << y << " + " << z << '\n';
   x = y - z;
   cout << "\nx = y - z:\n" << x << " = " << y << " - " << z << '\n';
   x = y * z;
   cout << "\nx = y * z:\n" << x << " = " << y << " * " << z << "\n\n";
   if ( x != k )
      cout << x << " != " << k << '\n';
   cout << '\n';
   x = k;
   if ( x == k )
      cout << x << " == " << k << '\n';
}

10.9(HugeInt类)

//HugeInt.h
#ifndef HUGEINT_H
#define HUGEINT_H

#include <iostream>
#include <string>
using namespace std;

class HugeInt
{
	friend ostream& operator<<(ostream&, const HugeInt&);
public:
	static const int digits = 30;
	HugeInt(long = 0);
	HugeInt(const string&);
	HugeInt operator+(const HugeInt&) const;
	HugeInt operator+(int) const;
	HugeInt operator+(const string&) const;
	bool operator==(const HugeInt&) const;
	bool operator!=(const HugeInt&) const;
	bool operator<(const HugeInt&) const;
	bool operator<=(const HugeInt&) const;
	bool operator>(const HugeInt&) const;
	bool operator>=(const HugeInt&) const;
	HugeInt operator-(const HugeInt&) const;
	HugeInt operator*(const HugeInt&) const;
	HugeInt operator/(const HugeInt&) const;
	int getLength() const;
private:
	short integer[digits];
};

#endif
//HugeInt.cpp
#include <iostream>
#include <cctype>
#include "HugeInt.h"
using namespace std;

HugeInt::HugeInt(long value)
{
    for (int i = 0; i < digits; i++)
        integer[i] = 0;
    for (int j = digits - 1; value != 0 && j >= 0; j--)
    {
        integer[j] = value % 10;
        value /= 10;
    }
}

HugeInt::HugeInt(const string& number)
{
    for (int i = 0; i < digits; i++)
        integer[i] = 0;
    int length = number.size();
    for (int j = digits - length, k = 0; j < digits; j++, k++)
        if (isdigit(number[k]))
            integer[j] = number[k] - '0';
}

int HugeInt::getLength() const
{
    int i;
    for (i = 0; i < digits; i++)
        if (integer[i] != 0)
            break;
    return digits - i;
}

HugeInt HugeInt::operator+(const HugeInt& op2) const
{
    HugeInt temp;
    int carry = 0;
    for (int i = digits - 1; i >= 0; i--)
    {
        temp.integer[i] = integer[i] + op2.integer[i] + carry;
        if (temp.integer[i] > 9)
        {
            temp.integer[i] %= 10;
            carry = 1;
        }
        else
            carry = 0;
    }
    return temp;
}

HugeInt HugeInt::operator+(int op2) const
{
    return *this + HugeInt(op2);
}

HugeInt HugeInt::operator+(const string& op2) const
{
    return *this + HugeInt(op2);
}

bool HugeInt::operator==(const HugeInt& op2) const
{
    for (int i = 0; i < digits; i++)
        if (op2.integer[i] != integer[i])
            return false;
    return true;
}

bool HugeInt::operator!=(const HugeInt& op2) const
{
    return !(*this == op2);
}

bool HugeInt::operator<(const HugeInt& op2) const
{
    for (int i = 0; i < digits; i++)
    {
        if (integer[i] == op2.integer[i])
            continue;
        else if (integer[i] > op2.integer[i])
            return false;
        else
            return true;
    }
    return false;
}

bool HugeInt::operator<=(const HugeInt& op2) const
{
    return !(*this > op2);
}

bool HugeInt::operator>(const HugeInt& op2) const
{
    return op2 < *this;
}

bool HugeInt::operator>=(const HugeInt& op2) const
{
    return !(*this < op2);
}

ostream& operator<<(ostream& output, const HugeInt& num)
{
    int i;
    for (i = 0; i < HugeInt::digits && num.integer[i] == 0; i++)
        ; // skip leading zeros
    if (i == HugeInt::digits)
        output << 0;
    else
        for (; i < HugeInt::digits; i++)
            output << num.integer[i];
    return output;
}

HugeInt HugeInt::operator-(const HugeInt& op2) const
{
    if (op2 > *this)
    {
        cout << "Error: Tried to subtract larger value from smaller value."
            << endl;
        return HugeInt("0");
    }
    HugeInt result("0");
    bool minusOne = false;
    for (int i = digits - 1; i >= 0; i--)
    {
        int topValue = this->integer[i];
        int bottomValue = op2.integer[i];
        if (minusOne)
        {
            if (topValue == 0)
                topValue = 9;
            else
            {
                topValue -= 1;
                minusOne = false;
            }
        }
        if (topValue >= bottomValue)
            result.integer[i] = topValue - bottomValue;
        else
        {
            topValue += 10;
            minusOne = true;
            result.integer[i] = topValue - bottomValue;
        }
    }
    return result;
}

HugeInt HugeInt::operator*(const HugeInt& op2) const
{
    int carryOver = 0;
    HugeInt total("0");
    HugeInt smaller = (*this < op2) ? *this : op2;
    HugeInt larger = (*this > op2) ? *this : op2;
    int x;
    for (x = 0; (x < digits) && (larger.integer[x] == 0); x++)
        ;
    int indexOfFirstDigitForLarger = x;
    for (int i = digits; i > digits - smaller.getLength(); i--)
    {
        HugeInt currentInt("0");
        int currentIntFrontHandle = i - 1;
        for (int j = digits; j > digits - larger.getLength(); j--)
        {
            int currentResult = carryOver +
                (larger.integer[j - 1] * smaller.integer[i - 1]);
            if (j - 1 == indexOfFirstDigitForLarger)
            {
                carryOver = 0;
                currentInt.integer[currentIntFrontHandle] =
                    currentResult % 10;
                currentIntFrontHandle -= 1;
                currentInt.integer[currentIntFrontHandle] =
                    currentResult / 10;
                currentIntFrontHandle -= 1;
            }
            else
            {
                carryOver = currentResult / 10;
                currentInt.integer[currentIntFrontHandle] =
                    currentResult % 10;
                currentIntFrontHandle -= 1;
            } 
        }
        total = total + currentInt;
    }
    return total; 
}

HugeInt HugeInt::operator/( const HugeInt &op2 ) const
{
   HugeInt remainderIntegers( *this );
   HugeInt currentValue( "0" );
   HugeInt result( "0" );
   int maxSolutionLength = this->getLength();
   for ( int i = digits - maxSolutionLength; i < digits; i++ )
   {
      currentValue = currentValue * HugeInt( "10" );
      currentValue.integer[ digits - 1 ] = remainderIntegers.integer[ i ];
      HugeInt tempResult( "0" );
      if ( op2 > currentValue )
         result.integer[ i ] = 0;
      else
      {
         int j;
         for ( j = 1; j <= 10; j++ )
         {
            HugeInt tempProduct = op2 * HugeInt( j );
            if ( tempProduct > currentValue )
               break;
         }
         result.integer[i] = j - 1;
         tempResult = op2 * HugeInt( j - 1 );
      }
      currentValue = currentValue - tempResult;
   }
   return result;
}
//main.cpp
#include <iostream>
#include "Hugeint.h"
using namespace std;

int main()
{
    HugeInt n1(7654321);
    HugeInt n2(7891234);
    HugeInt n3("99999999999999999999999999999");
    HugeInt n4("1");
    HugeInt n5("12341234");
    HugeInt n6("7888");
    HugeInt result;
    cout << "n1 is " << n1 << "\nn2 is " << n2
        << "\nn3 is " << n3 << "\nn4 is " << n4
        << "\nn5 is " << n5 << "\nn6 is " << n6
        << "\nresult is " << result << "\n\n";
    if (n1 == n2)
        cout << "n1 equals n2" << endl;
    if (n1 != n2)
        cout << "n1 is not equal to n2" << endl;
    if (n1 < n2)
        cout << "n1 is less than n2" << endl;
    if (n1 <= n2)
        cout << "n1 is less than or equal to n2" << endl;
    if (n1 > n2)
        cout << "n1 is greater than n2" << endl;
    if (n1 >= n2)
        cout << "n1 is greater than or equal to n2" << endl;
    result = n1 + n2;
    cout << n1 << " + " << n2 << " = " << result << "\n\n";
    cout << n3 << " + " << n4 << "\n= " << (n3 + n4) << "\n\n";
    result = n1 + 9;
    cout << n1 << " + " << 9 << " = " << result << endl;
    result = n2 + "10000";
    cout << n2 << " + " << "10000" << " = " << result << endl;
    result = n5 * n6;
    cout << n5 << " * " << n6 << " = " << result << endl;
    result = n5 - n6;
    cout << n5 << " - " << n6 << " = " << result << endl;
    result = n5 / n6;
    cout << n5 << " / " << n6 << " = " << result << endl;
}

10.10(RationalNumber类)

//RationalNumber.h
#ifndef RATIONAL_NUMBER_H
#define RATIONAL_NUMBER_H

class RationalNumber
{
public:
	RationalNumber(int = 0, int = 1);
	RationalNumber operator+(const RationalNumber&);
	RationalNumber operator-(const RationalNumber&);
	RationalNumber operator*(const RationalNumber&);
	RationalNumber operator/(const RationalNumber&);
	bool operator<(const RationalNumber&) const;
	bool operator>(const RationalNumber&) const;
	bool operator<=(const RationalNumber&) const;
	bool operator>=(const RationalNumber&) const;
	bool operator==(const RationalNumber&) const;
	bool operator!=(const RationalNumber&) const;
	void printRational() const;
private:
	int numerator;
	int denominator;
	void reduction();
};

#endif
//RationalNumber.cpp
#include <cstdlib>
#include <iostream>
#include "RationalNumber.h"
using namespace std;

RationalNumber::RationalNumber(int n, int d)
{
    numerator = n;
    denominator = (d > 0) ? d : 1;
    reduction();
}

RationalNumber RationalNumber::operator+(const RationalNumber& a)
{
    return RationalNumber(
        numerator * a.denominator + denominator * a.numerator,
        denominator * a.denominator);
}

RationalNumber RationalNumber::operator-(const RationalNumber& s)
{
    return RationalNumber(
        numerator * s.denominator - denominator * s.numerator,
        denominator * s.denominator);
}

RationalNumber RationalNumber::operator*(const RationalNumber& m)
{
    return RationalNumber(numerator * m.numerator,
        denominator * m.denominator);
}

RationalNumber RationalNumber::operator/(const RationalNumber& d)
{
    if (d.numerator != 0) // check for a zero in numerator
    {
        return RationalNumber(numerator * d.denominator,
            denominator * d.numerator);
    }
    else
    {
        cout << "Divide by zero error: terminating program" << endl;
        exit(1);
    }
}

bool RationalNumber::operator<(const RationalNumber& lr) const
{
    double thisVal = static_cast<double>(numerator) / denominator;
    double lrVal = static_cast<double>(lr.numerator) / lr.denominator;
    return thisVal < lrVal;
}

bool RationalNumber::operator>(const RationalNumber& gr) const
{
    return gr < *this;
}

bool RationalNumber::operator<=(const RationalNumber& ler) const
{
    return !(*this > ler);
}

bool RationalNumber::operator>=(const RationalNumber& ger) const
{
    return !(*this < ger);
}

bool RationalNumber::operator==(const RationalNumber& er) const
{
    return numerator == er.numerator && denominator == er.denominator;
}

bool RationalNumber::operator!=(const RationalNumber& ner) const
{
    return !(*this == ner);
}

void RationalNumber::printRational() const
{
    if (numerator == 0)
        cout << numerator;
    else if (denominator == 1)
        cout << numerator;
    else
        cout << numerator << '/' << denominator;
}

void RationalNumber::reduction()
{
    int largest, gcd = 1;
    largest = (numerator > denominator) ? numerator : denominator;
    for (int loop = 2; loop <= largest; loop++)
        if (numerator % loop == 0 && denominator % loop == 0)
            gcd = loop;
    numerator /= gcd;
    denominator /= gcd;
}
//main.cpp
#include <iostream> 
#include "RationalNumber.h"
using namespace std;

int main()
{
   RationalNumber c( 7, 3 ), d( 3, 9 ), x;
   c.printRational();
   cout << " + " ;
   d.printRational();
   cout << " = ";
   x = c + d;
   x.printRational();
   cout << '\n';
   c.printRational();
   cout << " - " ;
   d.printRational();
   cout << " = ";
   x = c - d;
   x.printRational();
   cout << '\n';
   c.printRational();
   cout << " * " ;
   d.printRational();
   cout << " = ";
   x = c * d;
   x.printRational();
   cout << '\n';
   c.printRational();
   cout << " / " ;
   d.printRational();
   cout << " = ";
   x = c / d;
   x.printRational();
   cout << '\n';
   c.printRational();
   cout << " is:\n";
   cout << ( ( c > d ) ? "  > " : "  <= " );
   d.printRational();
   cout << " according to the overloaded > operator\n";
   cout << ( ( c < d ) ? "  < " : "  >= " );
   d.printRational();
   cout << " according to the overloaded < operator\n";
   cout << ( ( c >= d ) ? "  >= " : "  < " );
   d.printRational();
   cout << " according to the overloaded >= operator\n";
   cout << ( ( c <= d ) ? "  <= " : "  > " );
   d.printRational();
   cout << " according to the overloaded <= operator\n";
   cout << ( ( c == d ) ? "  == " : "  != " );
   d.printRational();
   cout << " according to the overloaded == operator\n";
   cout << ( ( c != d ) ? "  != " : "  == " );
   d.printRational();
   cout << " according to the overloaded != operator" << endl;
}

10.11(Polynomial类)

//Polynomial.h
#ifndef POLYNOMIAL_H
#define POLYNOMIAL_H

class Polynomial
{
public:
	static const int maxTerms = 100;
	Polynomial();
	Polynomial operator+(const Polynomial&) const;
	Polynomial operator-(const Polynomial&) const;
	Polynomial operator*(const Polynomial&) const;
	Polynomial& operator=(const Polynomial&);
	Polynomial& operator+=(const Polynomial&);
	Polynomial& operator-=(const Polynomial&);
	Polynomial& operator*=(const Polynomial&);
	void enterTerms();
	void printPolynomial() const;
	int getNumberOfTerms() const;
	int getTermExponent(int) const;
	int getTermCoefficient(int) const;
	void setCoefficient(int, int);
	~Polynomial();
private:
	int numberOfTerms;
	int exponents[maxTerms];
	int coefficients[maxTerms];
	static void polynomialCombine(Polynomial&);
};

#endif
#include <iostream> 
#include <iomanip> 
#include "Polynomial.h"
using namespace std;

Polynomial::Polynomial()
{
    for (int t = 0; t < maxTerms; t++)
    {
        coefficients[t] = 0;
        exponents[t] = 0;
    }
    numberOfTerms = 0;
}

void Polynomial::printPolynomial() const
{
    int start;
    bool zero = false;
    if (coefficients[0])
    {
        cout << coefficients[0];
        start = 1;
        zero = true;
    }
    else
    {
        if (coefficients[1])
        {
            cout << coefficients[1] << 'x';
            if ((exponents[1] != 0) && (exponents[1] != 1))
                cout << '^' << exponents[1];
            zero = true;
        }
        start = 2;
    }
    for (int x = start; x < maxTerms; x++)
    {
        if (coefficients[x] != 0)
        {
            cout << showpos << coefficients[x] << noshowpos << 'x';
            if ((exponents[x] != 0) && (exponents[x] != 1))
                cout << '^' << exponents[x];
            zero = true;
        }
    }
    if (!zero)
        cout << '0';
    cout << endl;
}

Polynomial& Polynomial::operator=(const Polynomial& r)
{
    exponents[0] = r.exponents[0];
    coefficients[0] = r.coefficients[0];
    for (int s = 1; s < maxTerms; s++)
    {
        if (r.exponents[s] != 0)
        {
            exponents[s] = r.exponents[s];
            coefficients[s] = r.coefficients[s];
        }
        else
        {
            if (exponents[s] == 0)
                break;
            exponents[s] = 0;
            coefficients[s] = 0;
        }
    }
    return *this;
}

Polynomial Polynomial::operator+(const Polynomial& r) const
{
    Polynomial temp;
    bool exponentExists;
    int s;
    temp.coefficients[0] = coefficients[0] + r.coefficients[0];
    for (s = 1; (s < maxTerms) && (r.exponents[s] != 0); s++)
    {
        temp.coefficients[s] = r.coefficients[s];
        temp.exponents[s] = r.exponents[s];
    } 
    for (int x = 1; x < maxTerms; x++)
    {
        exponentExists = false; 
        for (int t = 1; (t < maxTerms) && (!exponentExists); t++)
            if (exponents[x] == temp.exponents[t])
            {
                temp.coefficients[t] += coefficients[x];
                exponentExists = true;
            }
        if (!exponentExists)
        {
            temp.exponents[s] = exponents[x];
            temp.coefficients[s] += coefficients[x];
            s++;
        }
    }
    return temp;
}

Polynomial &Polynomial::operator+=( const Polynomial &r )
{
   *this = *this + r;
   return *this;
}

Polynomial Polynomial::operator-(const Polynomial& r) const
{
    Polynomial temp;
    bool exponentExists;
    int s;
    temp.coefficients[0] = coefficients[0] - r.coefficients[0];
    for (s = 1; (s < maxTerms) && (exponents[s] != 0); s++)
    {
        temp.coefficients[s] = coefficients[s];
        temp.exponents[s] = exponents[s];
    }
    for (int x = 1; x < maxTerms; x++)
    {
        exponentExists = false;
        for (int t = 1; (t < maxTerms) && (!exponentExists); t++)
            if (r.exponents[x] == temp.exponents[t])
            {
                temp.coefficients[t] -= r.coefficients[x];
                exponentExists = true;
            }
        if (!exponentExists)
        {
            temp.exponents[s] = r.exponents[x];
            temp.coefficients[s] -= r.coefficients[x];
            s++;
        }
    }
    return temp;
}

Polynomial& Polynomial::operator-=(const Polynomial& r)
{
    *this = *this - r;
    return *this;
}

Polynomial Polynomial::operator*(const Polynomial& r) const
{
    Polynomial temp;
    int s = 1;
    for (int x = 0; (x < maxTerms) &&
        (x == 0 || coefficients[x] != 0); x++)
        for (int y = 0; (y < maxTerms) &&
            (y == 0 || r.coefficients[y] != 0); y++)
            if (coefficients[x] * r.coefficients[y])
                if ((exponents[x] == 0) && (r.exponents[y] == 0))
                    temp.coefficients[0] += coefficients[x] * r.coefficients[y];
                else
                {
                    temp.coefficients[s] =
                        coefficients[x] * r.coefficients[y];
                    temp.exponents[s] = exponents[x] + r.exponents[y];
                    s++;
                }
    polynomialCombine(temp);
    return temp;
}

void Polynomial::polynomialCombine(Polynomial& w)
{
    Polynomial temp = w;
    for (int x = 0; x < maxTerms; x++)
    {
        w.coefficients[x] = 0;
        w.exponents[x] = 0;
    }
    for (int x = 1; x < maxTerms; x++)
    {
        for (int y = x + 1; y < maxTerms; y++)
            if (temp.exponents[x] == temp.exponents[y])
            {
                temp.coefficients[x] += temp.coefficients[y];
                temp.exponents[y] = 0;
                temp.coefficients[y] = 0;
            }
    }
    w = temp;
}

Polynomial &Polynomial::operator*=( const Polynomial &r )
{
   *this = *this * r;
   return *this;
}

void Polynomial::enterTerms()
{
    bool found = false;
    int c, e, term;
    cout << "\nEnter number of polynomial terms: ";
    cin >> numberOfTerms;
    for (int n = 0; n < maxTerms && n < numberOfTerms; n++)
    {
        cout << "\nEnter coefficient: ";
        cin >> c;
        cout << "Enter exponent: ";
        cin >> e;
        if (c != 0)
        {
            if (e == 0)
            {
                coefficients[0] += c;
                continue;
            }
            for (term = 1; (term < maxTerms) &&
                (coefficients[term] != 0); term++)
                if (e == exponents[term])
                {
                    coefficients[term] += c;
                    exponents[term] = e;
                    found = true;
                }
            if (!found)
            {
                coefficients[term] += c;
                exponents[term] = e;
            }
        }
    }
}

int Polynomial::getNumberOfTerms() const
{
   return numberOfTerms;
}

int Polynomial::getTermExponent( int term ) const
{
   return exponents[ term ];
}

int Polynomial::getTermCoefficient( int term ) const
{
   return coefficients[ term ];
}

void Polynomial::setCoefficient( int term, int coefficient )
{
   if ( coefficients[ term ] == 0 ) // no term at this location
      cout << "No term at this location, cannot set term." << endl;
   else 
      coefficients[ term ] = coefficient;
}

Polynomial::~Polynomial()
{
}
//main.cpp
#include <iostream> 
#include "Polynomial.h"
using namespace std;

int main()
{
   Polynomial a, b, c, t;
   a.enterTerms();
   b.enterTerms();
   t = a; 
   cout << "First polynomial is:\n";
   a.printPolynomial();
   cout << "Second polynomial is:\n";
   b.printPolynomial();
   cout << "\nAdding the polynomials yields:\n";
   c = a + b;
   c.printPolynomial();
   cout << "\n+= the polynomials yields:\n";
   a += b;
   a.printPolynomial();
   cout << "\nSubtracting the polynomials yields:\n";
   a = t;
   c = a - b;
   c.printPolynomial();
   cout << "\n-= the polynomials yields:\n";
   a -= b;
   a.printPolynomial();
   cout << "\nMultiplying the polynomials yields:\n";
   a = t;
   c = a * b;
   c.printPolynomial();
   cout << "\n*= the polynomials yields:\n";
   a *= b;
   a.printPolynomial();
   cout << endl;
}

第十一章

11.