3.3 Classes in C++ 75
inti;
for(i = 0; i < length; i++){// (C++ arrays start at 0)
A[i] = w.A[i];// fill in teh vector w
}
return *this;
}
// return of*this, i.e. a Vector&, allows nested operations
u = v = u_vec = v_vec;
where we have used theredimfunction
v.redim(n);// make a vector v of length n
boolVector::redim (intn)
{
if(length == n)
returnfalse;// no need to allocate anything
else{
if(A != NULL){
// "this" object has already allocated memory
deallocate();
}
allocate(n);
returntrue;// the length was changed
}
}
and the copy action is defined as
Vector v(w);// take a copy of w
Vector::Vector (constVector& w)
{
allocate (w.size());// "this" object gets w's length
*this= w; // call operator =
}
Here we have definedthisto be a pointer to the current (“this”) object, in other wordsthis
is the object itself.
voidVector::print (std::ostream& o)const
{
inti;
for(i = 1; i <= length; i++)
o <<"("<< i <<")="<< (*this)(i) <<'\n';
}
doublea = v.inner(w);
doubleVector::inner (constVector& w)const
{
inti;doublesum = 0;
for(i = 0; i < length; i++)
sum += A[i]w.A[i];
// alternative:
// for (i = 1; i <= length; i++) sum += (this)(i)*w(i);
returnsum;
}
// Vector v
cout << v;