c++ - Operator overloading as friend function error -
i'm trying use + add 2 vector (mathematical vector). here's code:
class vector{ double v[max_size]; int dim; public: int getdim() const; vector(); vector(int n); vector(const vector& a); vector add(const vector&b); friend vector operator+(vector summand1, vector summand2); };
operator overloading:
vector operator+(vector summand1, vector summand2){ int dim1 = summand1.getdim(); int dim2 = summand2.getdim(); assert(dim1 == dim2); vector sum(dim1); int i; for(i = 0; < dim1; i++){ sum.v[i] = summand1.v[i] + summand2.v[i]; } return sum; }
and how use it:
vector m = v+t;
when run code, shows m (0,0) (2d vector), default value generated constructor. what's wrong it? thanks!
your copy constructor:
vector::vector(const vector& a){ dim = a.dim; vector(dim); }
correctly sets value of dim
member, has not other side effect.
you should have variant of following code:
vector::vector(const vector& a) : dim(a.dim) { std::copy(std::begin(a.v), std::end(a.v), v); }
this copy data present in parameter, , see correct behavior code:
// copy constructor called here, did not correctly copy data before. vector m = v + t;
for better (by intend simpler , safer) vector class, if have access compiler @ least c++11 compliant, can write:
class vector{ std::array<double, max_size> v; // note std::array here. int dim; public: int getdim() const; vector(); vector(int n); vector(const vector& a); vector add(const vector&b); friend vector operator+(vector summand1, vector summand2); };
the std::array
take care of everything, provided write copy constructor this:
vector::vector(const vector& a) : v(a.v), dim(a.dim) { }
or, better, let compiler generate copy constructor itself, same behavior.
Comments
Post a Comment