This is the source file vector.h which declares the vector class.
#ifndef VECTOR_H
#define VECTOR_H
#define DIMENSION 10 // maximum dimension
class vector
{
public:
vector();
vector( const vector & );
double &operator [] ( int );
const double &operator[]( int ) const;
const vector &operator = ( const vector & );
vector operator + ( const vector & );
vector operator * ( const double );
private:
double vp[DIMENSION]; // the vector
};
#endif
This is the source file vector.cpp which defines methods for the vector class
#include "stdafx.h"
#include "vector.h"
#include <assert.h>
/*----------------------------------------------------------------------------*
** "vector" default constructor, initializes elements of the vector to zero.
**
** returns: nothing
*/
vector::vector()
{
int i;
for( i = 0; i < DIMENSION; i++ ) // initialize to all zeroes
vp[i] = 0.0;
}
/*----------------------------------------------------------------------------*
** "vector" copy constructor, initializes elements of the vector to be
** equal to the values of the argument vector.
**
** returns: nothing
*/
vector::vector( const vector © ) // the vector to copy
{
int i;
for( i = 0; i < DIMENSION; i++ ) // copy into new vector
vp[i] = copy.vp[i];
}
/*----------------------------------------------------------------------------*
** "operator =" assigns the right hand side to this vector.
**
** returns: nothing
*/
const vector &vector::operator = ( const vector &rhs )
{
int i;
if( &rhs != this ) // prevent assignment to self
{
for( i = 0; i < DIMENSION; i++ ) // copy into this vector
vp[i] = rhs.vp[i];
}
return *this; // enable x = y = z;
}
/*----------------------------------------------------------------------------*
** "operator []" assigns value to element on left hand side.
**
** returns: value assigned
*/
double &vector::operator [] ( int i ) // subscript
{
assert( 0 <= i && i < DIMENSION ); // subscript must be in range
return vp[i];
}
/*----------------------------------------------------------------------------*
** "operator []" create value for right hand side
**
** returns: value to assign
*/
const double &vector::operator [] ( int i ) const
{
assert( 0 <= i && i < DIMENSION ); // subscript must be in range
return vp[i];
}
/*----------------------------------------------------------------------------*
** "operator +" performs vector addition.
**
** returns: pointer to vector
*/
vector vector::operator + ( const vector &rhs )
{
int i;
vector rv;
for( i = 0; i < DIMENSION; i++ ) // sum and copy into
rv[i] = vp[i] + rhs.vp[i]; // left hand side
return rv;
}
/*----------------------------------------------------------------------------*
** "operator *" multiplies the vector by a real number.
**
** returns: pointer to vector
*/
vector vector::operator * ( const double val )
{
int i;
vector rv;
for( i = 0; i < DIMENSION; i++ ) // multiply and copy into
rv[i] = vp[i] * val; // left hand side
return rv;
}