I want to add an overload operator #include<iostream> using namespace std; class
ID: 3859946 • Letter: I
Question
I want to add an overload operator
#include<iostream>
using namespace std;
class Poly {
int degree;
float *coEff;
public:
~Poly() { delete[] coEff; }
void display(ostream &out) {
out << coEff[0];
for (int i = 1; i<degree + 1; i++) out << "+" << coEff[i] << "x^" << i;
cout << endl;
}
void input(istream &in) {
cout << "Enter degree of the polynomial ";
in >> degree;
coEff = new float[degree + 1];
for (int i = 0; i <= degree; i++) { cout << "Enter " << i << "st Cofficient"; in >> coEff[i]; }
}
Poly() {};
Poly(Poly &P) {
degree = P.degree;
coEff = new float[P.degree + 1];
for (int i = 0; i <= P.degree; i++) coEff[i] = P.coEff[i];
}
void operator=( Poly &P) {
delete[] coEff;
degree = P.degree;
coEff = new float[P.degree + 1];
for (int i = 0; i <= P.degree; i++) coEff[i] = P.coEff[i];
}
friend Poly operator+(Poly &P1, Poly &P2);
};
Poly operator+(Poly &P1, Poly &P2) { // implements P = P1 + P2
Poly P;
P.degree = (P1.degree > P2.degree ? P1.degree : P2.degree);
P.coEff = new float[P.degree + 1];
// finish the code from here..
return P;
}
ostream & operator<<(ostream &out, Poly &P) { P.display(out); return out; }
istream & operator>>(istream &in, Poly &P) { P.input(in); return in; }
Explanation / Answer
Poly operator+(Poly &P1, Poly &P2) { // implements P = P1 + P2
Poly P;
P.degree = (P1.degree > P2.degree ? P1.degree : P2.degree);
P.coEff = new float[P.degree + 1];
// finish the code from here..
if(P1.degree < P2.degree){
int i = 0;
for(;i< P1.degree+1; ++i ){
P.coEff[i] = P1.coEff[i] + P2.coEff[i];
}
for(; i< P2.degree+1; ++i){
P.coEff[i] = P2.coEff[i];
}
}else if(P1.degree == P2.degree){
int i=0;
for(; i< P1.degree+1; ++i){
P.coEff[i] = P1.coEff[i] + P2.coEff[i];
}
}else{
int i=0;
for(; i< P2.degree+1; ++i){
P.coEff[i] = P1.coEff[i] + P2.coEff[i];
}
for(; i< P1.degree+1; ++i){
P.coEff[i] = P1.coEff[i];
}
}
return P;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.