c++ - My + operator changing the value of my class -


 const polynomial operator +(const polynomial lhs, const polynomial rhs){         //lhs 1         polynomial result(lhs);          result+=rhs;         //when add rhs result increments lhs , lhs 3         cout<<"item: "<<rhs<<endl;         return result;     }          int size;     monomial *polynome; // polynome array of monomials                             //p[0]= 2, p[1]=3x etc. 

i using default copy constructor(i didnt define one) maybe thats problem since have pointer array dont know. rather not share += operator unles necessary since seem working fine terribly implemented take 30 minutes explain whats going on. driving me crazy, solutions?

edit: defining deep copy constructor solved problem. lot tips!

i'm going hazard wild guess class looks vaguely this:

// not write code this. default copy semantics incorrect. struct polynomial {     polynomial(size_t order) : coefs(new double[order+1]) {}     double * coefs; }; 

attempting manage dynamic memory dumb pointer. unless write own copy constructor , assignment operator correctly copy dynamic array, copying copy pointer, leaving both pointing same array.

the simplest solution use standard vector container, has copy semantics you'd expect:

// better: default copy semantics correctly copy vector struct polynomial {     polynomial(size_t order) : coefs(order+1) {}     std::vector<double> coefs; }; 

Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -