samedi 4 mars 2017

"+" operator overloading in c++

I am making a program of getting polynomial and using + operator overloading but whenever i try to run this, my system crashes and an error message is displayed . i do not know what went wrong with this code.

#include "poly.h"
#include<iostream>
#include<cmath>
using namespace std;

ostream& operator<<(ostream& os, const poly& pol){
    int x=3;
    for(int i=0; i< pol.degree ; i++){
    os <<"Co-efficient is "<<pol.getCoef(i) <<" x^ "<<x<<endl;
    x--;
    }
    return os;
}
poly::poly (){

}

poly::poly (int d){
    degree = d;
    t=new float[degree+1];

}


void poly::setCoef(){ //compulsory called
    float *coef=t;
    for(int i=0 ;i<degree; i++){
    cout<<endl<<"Enter co-efficient for polynomial\t";
    cin>>coef[i];
    }

}

void poly::setCoefOf ( int i, float j){ //setting co-efficient at specific place
if(i>=0 && i<=degree )
t[i]=j;
}



float poly::getCoef ( int a) const{
if(a >= 0&& a<= degree)
    return t[a];
else
    return 0;

}

int poly::getDegree ( ) const{
    return degree;
}


poly poly::operator+(const poly &p1) const{
poly temp;
for(int i = 0 ; i<3 ; i++){
    temp.t[i] = p1.t[i] + t[i] ;
    }

   return (temp);

}

This is main

#include "poly.h"
#include <iostream>
#include<cmath>
using namespace std;

int main()
{
poly p(3);
poly p1(3);
poly p2;
p.setCoef();
p1.setCoef();
cout<<endl<<p;
cout<<endl<<p1;

p2 = p + p1;

cout<<p2;

}

Aucun commentaire:

Enregistrer un commentaire