// Source: "Software Design ...", John A Robinson, Newnes, 2004, page 129. const int max_dimensions = 8; class real_vector { int dimensions; double vector_base[max_dimensions]; // The vector itself is stored in this array public: real_vector(const int ndim) // The constructor takes a parameter which specifies // how many dimensions this vector is to have { if (ndim > max_dimensions) dimensions = max_dimensions; else dimensions = ndim; } ~real_vector() // The destructor does not have to do any tidying up, // so it is empty. { } int set_component(const int comp, const double value); int get_component(const int comp, double& value) const; int tell_num_dimensions() const { return(dimensions); } real_vector sum_with_me(const real_vector& u); // Returns a vector sum double dot_with_me(const real_vector& u); // Returns dot product }; int real_vector::set_component(const int comp, const double value) { if ((comp < 0) || (comp > dimensions-1)) return(-1); vector_base[comp] = value; return(0); } int real_vector::get_component(const int comp, double& value) const { if ((comp < 0) || (comp > dimensions-1)) return(-1); value = vector_base[comp]; return(0); } real_vector real_vector::sum_with_me(const real_vector& u) // Returns a vector that is the sum of this object and the // vector given as a parameter { real_vector sum(dimensions); // Set up a vector with the same number // of dimensions as me. if (u.tell_num_dimensions() != dimensions) // *** // If the vector I am being summed with has a different number of dimensions return(sum); // Essentially an error return -- zero vector for (int i = 0; i < dimensions; i++) sum.vector_base[i] = u.vector_base[i] + vector_base[i]; // +++ return(sum); } double real_vector::dot_with_me(const real_vector& u) // Returns dot product of this object and the vector given as a parameter. // (The dot product multiplies each pair of components, then sums the results) { double dot_product = 0; if (u.dimensions != dimensions) return(dot_product); for (int i = 0; i < dimensions; i++) dot_product += u.vector_base[i] * vector_base[i]; // +++ return(dot_product); } #include using namespace std; // Next line commented out in online version because all code is in this one file. // #include "vec_def.h" // Including the above vector class definition file int main() { real_vector a(3), b(3); // These will be set up as three dimensional vectors a.set_component(0,0.0); a.set_component(1,1.0); a.set_component(2,2.0); b.set_component(0,3.0); b.set_component(1,4.0); b.set_component(2,5.0); real_vector c = a.sum_with_me(b); double x, y, z; c.get_component(0,x); c.get_component(1,y); c.get_component(2,z); cout << x << ", " << y << ", " << z << "\n"; return 0; }