3.3 Classes in C++ 83
Vector::Vector(int_length,// length of the array
const double*array){// one-dimensioal array
length =_length;
vec =new double[length];
for(inti=0; i<length; i++)
vec[i] = array[i];
}
// copy constructor
Vector::Vector(constVector& w){
vec =new double[length = w.length];
for(inti=0; i<length; i++)
vec[i] = w[i];// This possible because we have overloaded the operator[]
// A more straigforward way of implementing this constructor is:
// vec = new double[length=w.length];
//*this = w; // Here we use the assignment operator=
}
// normalize a vector
voidVector::normalize(){
doubletmp = 1.0/l2norm();
for(inti=0;i<length; i++)
vec[i] = vec[i]*tmp;
}
voidVector::print(std::ostream& os)const{
inti;
for(i=0; i<length; i++){
os <<"("<< i <<") = "<< vec[i] <<"\n";
}
}
// change the length of a vector
boolVector::redim(int_length){
if(length ==_length)
returnfalse;
else{
if(vec != NULL){
delete[] vec;
}
length =_length;
vec =new double[length];
returntrue;
}
}
boolVector::indexOk(inti)const{
if(i<0 || i>=length){
std::cerr <<"vector index check; index i="<< i
<<" out of bounds 0:"<< length-1
<< std::endl;
returnfalse;
}
else
returntrue;// valid index!
}
/**/
/ DEFINITION OF OPERATORS /
/**/