Tuesday, 15 May 2012

C++ - Array values in class member function changing spontaneously -



C++ - Array values in class member function changing spontaneously -

i'm having issues overloading *= operator in polynomial class. i've included believed relevant solving problem below. apologize length of code.

here parts of class header think relevant.

#ifndef pol_h #define pol_h #include <string> #include <iostream> #include <vector> #include <cmath> using namespace std; class pol { // private info members string polname; // polynomial name int degree; // polynomial grade int *coef; // array polynomial coefficients public: // constructors pol(string, int, int*); // input name, grade // , array of coefficients // operator overloading pol operator *= (pol); // other methods void printpol ();

here .c file overload of *=. decided not include printpol method long , i'm 100% sure problem not lie it.

#include "pol.h" pol::pol (string s, int d, int *c) { grade = d; polname = s; coef = new int [degree + 1]; coef = c; // initializes polynomial of grade d c coefficients // named s } pol pol::operator *= (pol p1) { int *cp = this->coef; // if print values stored in cp @ point // alright (int = p1.degree; >= 0; --i) { (int j = this->degree; j >= 0; --j) { this->coef[i + j] += p1.coef[i] * cp[j]; cout << cp[j] << endl; // when print values here, they've changed! } } this->degree += p1.degree; homecoming *this; }

my first thought maybe overstepping bounds of array, size of array cp create this->degree, , highest value "j" assumes, think can't it.

here main function. uncertainty problem here, included anyway, see how i'm using methods i've declared.

#include "pol.h" #include <iostream> using namespace std; int main () { int [9] = {0, 0, 2, 4, 0, 0, 5, 0, 1}; int b [5] = {4, -2, 0, 0, 1}; pol p2 ("p2", 4, b); pol p4 ("p4", 8, a); p4*= p2; p4.printpol(); homecoming 0; }

this obvious , i'm making ass out of myself, i've staring @ code hours , can't figure out. in advance.

you're asking overloading *=, yet problem has nil *=. array values changing "spontaneously", yet you're changing them yourself, right there in code.

int *cp = this->coef; // "if print values stored in cp @ point // alright" (int = p1.degree; >= 0; --i) { (int j = this->degree; j >= 0; --j) { this->coef[i + j] += p1.coef[i] * cp[j]; // <-- well, changed them here mate cout << cp[j] << endl; // "when print values here, they've changed!" } }

from way commented coef's declaration:

int *coef; // array polynomial coefficients

it seems think coef array; it's not. seem think assigning coef int* re-create underlying info points to; not.

coef pointer, , assigning pointer copies pointer.

try using std::vector else info ownership , lifetime managed you, , may take advantage of basic assignment operations.

c++ arrays class

No comments:

Post a Comment