重载加法运算符以添加两个多项式
Posted
技术标签:
【中文标题】重载加法运算符以添加两个多项式【英文标题】:Overload addition operator to add two polynomials 【发布时间】:2016-10-28 15:49:13 【问题描述】:我正在尝试。我的想法是将多项式制作为两个数组,一个用于系数,一个用于指数。添加两个多项式只是将两个数组组合成一个更长的数组。我刚刚学习了指针和 & 符号,但不知道如何有效地使用它们。我收到错误消息说“表达式必须是可修改的左值”。
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】:您已将运算符 + 声明为 const:
Polynomial Polynomial::operator + (const Polynomial &right) const
^^^^^
这意味着 this-> 系数[*] 不能被修改。即您创建了一个 Sum 对象,但正尝试写入 *this 而不是您返回的 Sum 对象。
【讨论】:
谢谢!但是无论如何将两个系数和指数数组与将运算符 + 声明为 const 结合起来? 您可以使用非成员函数(可能声明为友元):多项式运算符 + ( const Polynomial &, const Polynomial & ) ; 但是这个Polynomial operator + ( const Polynomial &, const Polynomial & ) 不是另一个接受两个参数的运算符重载函数吗? 我已经澄清了我的回应。 现在我明白了!谢谢!以上是关于重载加法运算符以添加两个多项式的主要内容,如果未能解决你的问题,请参考以下文章