我正在研究一个表示多项式的简单类。我在x矢量中存储x的系数和等效功率。分配某些术语的方式必须如测试文件中所示。它需要我提供的一些操作员超载。问题在于它除了最后一个之外还分配了适当的系数,另外每个项都具有第一个赋值的x的幂。
期望的输出:
多项式p1:2x ^ 3 + 3.6x + 7x ^ 0
多项式p2:3x ^ 1 + 6x ^ 2 + 1x ^ 4
实际输出:
多项式p1:5x ^ 3 + 2x ^ 3 + 3.6x ^ 3
多项式p2:5x ^ 1 + 3x ^ 1 + 6x ^ 1
你知道这是怎么回事吗?我
Polynomials.cpp
double & Polynomials::operator[]( int power_of_x ){
this->coeff_and_power.push_back(5.0); // dummy variable 5.0 just to alloc 'cell' for coefficient
this->coeff_and_power.push_back( (double) power_of_x ); //assigning power of x
this->polynomial_terms.push_back( coeff_and_power ); // polynomial_terms vector contains collection of 2 elements vectors( coefficient and power ) indicating certain term of a function
return (coeff_and_power[0]); //coefficient to be assigned in main(returning by reference) function
}
std::ostream& operator<<(std::ostream& out, const Polynomials & toWrite){
for(unsigned int i = 0; i < toWrite.polynomial_terms.size(); i++){
if(i){
out<<" + ";
}
out<<toWrite.polynomial_terms[i][0]<<"x^"<<toWrite.polynomial_terms[i][1];
}
return out;
}
TEST.CPP
#include <iostream>
#include "Polynomials.h"
using namespace std;
int main(void) {
Polynomials p1;
p1[3] = 2; p1[1] = 3.6; p1[0] = 7;
Polynomials p2;
p2[1] = 3; p2[2] = 6; p2[4] = 1;
cout << "Polynomial p1: " << p1 << endl;
cout << "Polynomial p2: " << p2 << endl;
}
答案 0 :(得分:0)
在你的operator[]
超载你push_back()
,但无条件。
return coeff_and_power[0];
返回front
进行作业
顺便说一句
this->polynomial_terms.push_back( coeff_and_power )
推送副本而不是引用,因为polynomial_terms
具有例如行为, STD:矢量