實現了一個多項式類,其中包含2維D數組,並將多個項作爲數據成員。數組行是係數,數組列是指數。我們的目標是超載+運算符做加法運算,即如果指數相同則加上係數,否則包括術語。具有二維數組成員的多項式類作爲數據成員並使用運算符+重載
輸出部分正確,輸出的最後一項不正確。請考慮運算符+重載並提供補救措施!在此先感謝...
請參閱注意刪除以前的缺陷。
#ifndef POLYNOMIAL_H
#define POLYNOMIAL_H
#include <iostream>
using namespace std;
#define MAX 10
class Polynomial {
public :
Polynomial();
//~Polynomial(){ delete [] terms[MAX]; } (see comments)
void enterTerms();
Polynomial operator +(const Polynomial &);
private :
int terms[MAX][2]; //define size statically if not using "new"
int n; //number of terms
};
#endif
#include "polynomial.h"
Polynomial Polynomial :: operator + (const Polynomial & p){
Polynomial temp, sum;
temp.n = n + p.n;
int common = 0;
//first write sum as concatenation of p1 and p2
for (int i = 0 ; i < n ; i++){
temp.terms[i][0] = terms[i][0];
temp.terms[i][1] = terms[i][1];
}
//notice j and k for traversing second half of sum, and whole p2 resp
for (int j = n, k = 0; j < n + p.n, k < p.n ; j++, k++){
temp.terms[j][0] = p.terms[k][0];
temp.terms[j][1] = p.terms[k][1];
}
for (int l = 0; l < temp.n - 1 ; l++){ // 0 to 1 less than length
for (int m = l + 1 ; m < temp.n ; m++){ // 1 more than l to length,so that compared pairs are non redundant
if(temp.terms[l][1] == temp.terms[m][1]){
common++; //common terms reduce no. of terms
temp.terms[l][0] += temp.terms[m][0]; //coefficients added of exponents same
temp.terms[m][0] = 0;
}
}
}
sum.n = temp.n - common;
for (int q = 0, r = 0; q < temp.n, r < sum.n; q++, r++){
if (temp.terms[q][0] == 0)
continue;
else if (temp.terms[q][0] != 0){
sum.terms[r][0] = temp.terms[q][0];
sum.terms[r][1] = temp.terms[q][1];
}
}
cout << sum;
return sum;
}
Polynomial :: Polynomial(){
for (int i = 0; i < MAX; i++){
terms[i][0] = 0;
terms[i][1] = 0;
}
}
void Polynomial :: enterTerms(){
int num;
cout<<"enter number of terms in polynomial\n";
cin >> num;
n = num >= 0 ? num : 1;
cout << "enter coefficient followed by exponent for each term in polynomial\n";
for (int i = 0; i < n ; i++)
cin >> terms[i][0] >> terms[i][1] ;
}
int main(){
Polynomial p1 , p2;
p1.enterTerms();
p2.enterTerms();
p1 + p2;
system("PAUSE");
return EXIT_SUCCESS;
}
你看我要刪除尚未分配了'new'運營商的陣列。這是錯誤的。 – legends2k
同意,所以我如何回收內存或我在析構函數看我的構造函數。 – ShivaniDhanked
在構造函數中,你只是初始化你的靜態數組。刪除sholuld只用於dynmaic分配 – 999k