// // class for 3D vectors of ints, plus test main // #include #include // has EXIT_SUCCESS // // class for 3D vectors of ints // class Vector { public: // ---- constructors ---- // post: x = init_x, y = init_y, z = init_z Vector(int init_x = 0, int init_y = 0, int init_z = 0) { x = init_x; y = init_y; z = init_z; } // ---- "constant" member functions ---- // post: return value is x coordinate int get_x(void) const { return x; } // post: return value is y coordinate int get_y(void) const { return y; } // post: return value is z coordinate int get_z(void) const { return z; } private: int x, y, z; }; // ---- "helper" functions ---- // post: return value is x + y int add(int x, int y) { return x + y; } // post: return value is x - y int subtract(int x, int y) { return x - y; } // post: return value is x * y int multiply(int x, int y) { return x * y; } // post: return value is produced by combining corresponding // elements of v1, v2 using oper Vector pairwiseOperator(const Vector & v1, const Vector & v2, int oper(const int, const int)) { return Vector(oper(v1.get_x(), v2.get_x()), oper(v1.get_y(), v2.get_y()), oper(v1.get_z(), v2.get_z())); } // post: return value is produced by "reducing" elements of // v1 using oper int reduce(const Vector & v1, int oper(const int, const int)) { return (oper( oper(v1.get_x(), v1.get_y()), v1.get_z())); } // ---- nonmember functions ---- // overloaded "+" // post: return value is sum of v1 and v2 Vector operator+ (const Vector & v1, const Vector & v2) { return pairwiseOperator(v1, v2, add); } // overloaded "-" // post: return value is difference of v1 and v2 Vector operator- (const Vector & v1, const Vector & v2) { return pairwiseOperator(v1, v2, subtract); } // overloaded "<<" // post: v printed to out, in the form (x, y, z) ostream & operator<< (ostream & out, const Vector & v) { out << "(" << v.get_x() << ", " << v.get_y() << ", " << v.get_z() << ")"; return out; } // dot product // postcondition: return value is dot product of v1, v2 int dotProduct(const Vector & v1, const Vector & v2) { return (reduce (pairwiseOperator(v1, v2, multiply), add)); } // // ---- main program to test a few things ---- // int main(void) { Vector v1(1, 2, 3); // note syntax for declaring/initializing Vector v2(2, 4, 6); cout << "v1 = " << v1 << endl; cout << "v2 = " << v2 << endl; Vector vtemp = v1 + v2; cout << "v1 + v2 = " << vtemp << endl; cout << "v1 - v2 = " << v1 - v2 << endl; // note compute-and-print cout << "dot product of v1 and v2 = " << dotProduct(v1, v2) << endl; return EXIT_SUCCESS; }