重载加法运算符以添加两个多项式

时间:2016-10-28 15:49:14

标签: operator-overloading lvalue

我试图重载加法运算符以添加两个多项式。我的想法是将多项式设为两个数组,一个用于系数,一个用于指数。添加两个多项式只是将两个数组合并为一个更长的数组。我刚刚学会了指针和&符号,但还不知道如何有效地使用它们。我得到的错误是"表达式必须是可修改的左值"。

getter和setter函数将用于组合相同指数的术语,我还没有写出来。

#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];
}

这是头文件

#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

1 个答案:

答案 0 :(得分:0)

您已将运算符+声明为const:

Polynomial Polynomial::operator + (const Polynomial &right) const
                                                            ^^^^^

这意味着这个 - &gt;系数[*]无法修改。即你已经创建了一个Sum对象,但是试图写入* this而不是你要返回的Sum对象。