c++ - How to correct the overloading assignment in this program? -
hello everyone: struggling assign cof of 1 class object class object. however, why overloading(=) can assign first 2 cofs!(cof pointer int)
i new here, not sure how enter mu code here. hope can me! thanks! code:
#include <iostream> using namespace std; class polynomial { private : int* cof; int size; public : polynomial(); polynomial(int ); polynomial(const polynomial& a); ~polynomial(); int getvalue() const; void operator =(const polynomial& a); void output(const polynomial& p); }; int main() { int m; cout<<"how many numbers in p1 :"<<endl; cin>>m; polynomial p1(m); cout<<"how many numbers in p2"<<endl; cin>>m; polynomial p2(m); cout<<"the p1's cof"<<endl; p1.output(p1); cout<<"the p2's cof"<<endl; p2.output(p2); polynomial t; t=p1; cout<<" t's cof:"<<endl; t.output(t); t=p2; cout<<"the t's cof:"<<endl; t.output(t); return 0; } polynomial::~polynomial() { delete [] cof;} polynomial:: polynomial():size(1) { cof= new int[size]; cof[0]=0; } polynomial::polynomial(int a): size(a) { cof= new int[size+1]; cout<<"please enter numbers:"<<endl; for(int i=0;i<size+1;i++) cin>>cof[i]; } polynomial::polynomial(const polynomial& a) { cof= new int[a.size+1]; for(int i=0;i<=a.size;i++) { cof[i]=a.cof[i];} } int polynomial::getvalue() const { return size;} void polynomial::output(const polynomial& p) { for(int i=0;i<=p.size;i++) { cout<<p.cof[i]<<" ";} cout<<endl; } void polynomial::operator =(const polynomial& a) { if (cof!=null) delete [] cof; int x=a.getvalue(); cof= new int[x+1]; for(int i=0;i<=x;i++) { cof[i]=a.cof[i];} }
you forgot copy size.
void polynomial::operator =(const polynomial& a) { if (cof!=null) delete [] cof; size = a.getvalue(); // <<< !!! cof = new int[size+1]; for(int = 0; < size + 1; i++){ cof[i]=a.cof[i];} } } coding easier if drop outdated c-style array , use std::vector instead. drop size (use vector's size) , copy vector.
also, calling getter (getvalue()) different member (size) apt cause confusion.
Comments
Post a Comment