I am trying to overload the addition operator to add two polynomials. My idea is that make the polynomial as two arrays, one for coefficients and one for exponents. Adding two polynomials is just combining two arrays into a longer array. I just learned pointers and ampersand yet not know how to use them efficiently. I got the errors saying "expression must be a modifiable lvalue".
The getter and setter functions will be used to combine the terms of same exponents and I haven't write it yet.
#include <iostream>
#include "Polynomial.h"
using namespace std;
Polynomial::Polynomial(){
};
Polynomial Polynomial::operator + (const Polynomial &right) const
{
Polynomial Sum;
Sum.numberOfTerms = numberOfTerms + right.numberOfTerms;
int i = static_cast<int>(numberOfTerms);
int j = static_cast<int>(right.numberOfTerms);
for (int n = 0; n > i && n <= n + j; n++) {
coefficients[n] = right.coefficients[n]; //error saying expression must be a modifiable lvalue
exponents[n] = right.exponents[n];
}
return Sum;
}
void Polynomial::enterTerms() {
int coefficient=0;
int exponent=0;
cout << "Enter number of terms for the polynomial:";
cin >> numberOfTerms;
for (int i = 0; i < numberOfTerms; i++) {
cout << "Enter coefficient:\n";
cin >>coefficient;
coefficients[i] = coefficient;
cout << "Enter exponent:\n";
cin >> exponent;
exponents[i] = exponent;
}
}
void Polynomial::printPolynomial() const {
//Print the first term out, if exponent is 0, just print out the constant
if (exponents[0] == 0) {
cout << coefficients[0];
}
else{
cout << coefficients[0] << "x^" << exponents[0];
}
//Print from the second term to the last term, including a "+" in front of each term
for (int i = 1; i <= numberOfTerms; i++) {
if (exponents[i] == 0) {
cout <<"+"<< coefficients[i];
}
else {
cout << "+"<<coefficients[i] << "x^" << exponents[i];
}
}
}
int Polynomial::getNumberOfTerms() const {
return numberOfTerms;
}
int Polynomial::getTermCoefficient(int i) const {
return coefficients[i];
}
int Polynomial::getTermExponent(int i) const {
return exponents[i];
}
This is the header file
#ifndef POLYNOMIAL_H
#define POLYNOMIAL_H
#include <array>
using namespace std;
class Polynomial {
public:
static const int maxTerms = 100;
Polynomial();
Polynomial operator+(const Polynomial &)const;
void enterTerms();
void printPolynomial() const;
int getNumberOfTerms() const;
int getTermExponent(int) const;
int getTermCoefficient(int) const;
void setCoefficient(int, int);
//~Polynomial();
private:
size_t numberOfTerms;
array<int, maxTerms> exponents;
array<int, maxTerms> coefficients;
static void polynomialCombine(Polynomial &);
};
#endif
You've declared your operator + as const:
Polynomial Polynomial::operator + (const Polynomial &right) const
^^^^^
which means that this-> coefficients[*] cannot be modified. i.e. You have created a Sum object, but are trying to write into *this instead of the Sum object that you are returning.