【发布时间】:2015-11-07 13:16:17
【问题描述】:
我正在研究一个表示多项式的简单类。我将 x 的系数和等效幂存储在 2D 向量中。分配某些术语的方式必须如测试文件中所示。它需要我提供的一些运算符重载。问题是除了最后一个之外,它还分配了适当的系数,另外每个项都具有第一个分配值的 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
你知道这是怎么回事吗?我
多项式.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;
}
【问题讨论】:
-
使用调试器并逐行执行。
-
为什么我会得到负利率?解决方案是如此明显还是什么?
-
欢迎来到 SO!由于您没有给我们重现错误的机会,因此可能会累积反对票;例如在我的答案中,我必须做一些猜测工作,并冒着因为我猜错而导致对该答案投反对票的风险。
标签: c++ vector operator-overloading